Skip to content

Instantly share code, notes, and snippets.

@lejarx
Forked from walkerke/animated_pyramid.R
Created February 26, 2016 02:44
Show Gist options
  • Save lejarx/bbd5f67bd9f993f6fe69 to your computer and use it in GitHub Desktop.
Save lejarx/bbd5f67bd9f993f6fe69 to your computer and use it in GitHub Desktop.
library(idbr) # devtools::install_github('walkerke/idbr')
library(ggplot2)
library(animation)
library(dplyr)
library(ggthemes)
idb_api_key("Put your Census API key here")
male <- idb1('CH', 2016:2050, sex = 'male') %>%
mutate(POP = POP * -1,
SEX = 'Male')
female <- idb1('CH', 2016:2050, sex = 'female') %>%
mutate(SEX = 'Female')
china <- rbind(male, female) %>%
mutate(abs_pop = abs(POP))
# Animate it with a for loop
saveGIF({
for (i in 2016:2050) {
title <- as.character(i)
year_data <- filter(china, time == i)
g1 <- ggplot(year_data, aes(x = AGE, y = POP, fill = SEX, width = 1)) +
coord_fixed() +
coord_flip() +
annotate('text', x = 98, y = 8000000,
label = 'Data source: US Census Bureau IDB via the idbr R package', size = 3.5) +
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(-10000000, 10000000, 5000000),
labels = paste0(as.character(c(seq(10, 0, -5), c(5, 10))), "m"),
limits = c(min(china$POP), max(china$POP))) +
theme_economist(base_size = 14) +
scale_fill_economist() +
ggtitle(paste0('Population structure of China, ', title)) +
ylab('Population') +
xlab('Age') +
theme(legend.position = "bottom") +
guides(fill = guide_legend(reverse = TRUE))
print(g1)
}
}, movie.name = 'china_pyramid.gif', interval = 0.1, ani.width = 700, ani.height = 600)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment