Visualising the expected population structure of Denmark 2019-2060 in R with ggplot2 and the animation package

Statistics Denmark has published the expected number of people living in Denmark from 2019 to 2060 by age and sex (table FRDK119 in statistikbanken). The numbers can be shown with an animation created by the R code below. The result is shown here.

### Load packages
library(ggplot2)
library(animation)
library(dplyr)
library(ggthemes)

### Read data and manipulate a bit
temp01<-read.csv("C:/Users/soren/Documents/omicron/hjemmeside/consula/befolkning/fremskrivning.csv",skip=2)

temp02<-temp01[2:107,2:44]
names(temp02)[1]<-"Age"
temp02$sex<-"Male"

temp03<-temp01[109:214,2:44]
names(temp03)[1]<-"Age"
temp03$sex<-"Female"

temp04<-rbind(temp02,temp03)
temp04$Age<-gsub("år og derover","",temp04$Age)
temp04$Age<-gsub("år","",temp04$Age)
temp04$Age_n<-as.numeric(temp04$Age)

# Animate it with a for loop
saveHTML({
for(i in 2:43){

year_data<-temp04[,c(i,44,45)]
names(year_data)<-c("POP","SEX","AGE")
year_data$POP[year_data$SEX=="Male"]<-year_data$POP[year_data$SEX=="Male"]*(-1)
title<-as.character(2017+i)

    
g1<-ggplot(year_data,aes(x=AGE,y=POP,fill=SEX,width=1))+
coord_fixed()+coord_flip()+ 
geom_bar(data=subset(year_data,SEX=="Female"),stat="identity")+
geom_bar(data=subset(year_data,SEX=="Male"),stat="identity")+
scale_y_continuous(breaks=seq(-40000,40000,20000),
labels=paste0(as.character(abs(seq(-40000,40000,20000)))), 
limits=c(-45000,45000))+
theme_economist(base_size=14)+ 
scale_fill_manual(values=c('#ff9896','#d62728'))+ 
ggtitle(paste0('Population structure of Denmark, ', title))+ 
ylab('Population')+ 
xlab('Age')+ 
theme(legend.position="bottom",legend.title=element_blank())+ 
guides(fill=guide_legend(reverse=TRUE))

print(g1)
}

}, img.name = "denmark_pyramid", imgdir = "denmark_pyramid", htmlfile = "denmark_pyramid.html", 
    outdir = getwd(), autobrowse = FALSE, interval=0.5, ani.height = 550, ani.width = 650, 
    verbose = FALSE, navigator=FALSE, autoplay = TRUE, title = "Population structure of Denmark")