Skip to content

Instantly share code, notes, and snippets.

@cavedave
Last active September 16, 2016 16:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cavedave/39219ef2f87fc5cff430c75954988864 to your computer and use it in GitHub Desktop.
Save cavedave/39219ef2f87fc5cff430c75954988864 to your computer and use it in GitHub Desktop.
Ireland population pyramid based on code from https://gist.github.com/walkerke/f9665e15b74b393bd2d6
library(idbr) # devtools::install_github('walkerke/idbr')
library(ggplot2)
library(animation)
library(dplyr)
library(ggthemes)
idb_api_key("")
male <- idb1('Ireland', 1996:2050, sex = 'male') %>%
mutate(POP = POP * -1,
SEX = 'Male')
female <- idb1('Ireland', 1996:2050, sex = 'female') %>%
mutate(SEX = 'Female')
ireland <- rbind(male, female) %>%
mutate(abs_pop = abs(POP))
# Animate it with a for loop
saveGIF({
for (i in 1996:2050) {
title <- as.character(i)
year_data <- filter(ireland, 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))), "k"),
#limits = c(min(ireland$POP), max(ireland$POP))) +
scale_y_continuous(breaks = seq(-100000, 100000, 10000),
labels = c('-100k', '-50k', '0','50k','100k','110k'),
limits = c(min(ireland$POP), max(ireland$POP)))+
theme_economist(base_size = 14) +
scale_fill_economist() +
ggtitle(paste0('Population Structure of Ireland, ', title)) +
ylab('Population') +
xlab('Age') +
theme(legend.position = "bottom") +
guides(fill = guide_legend(reverse = TRUE))
print(g1)
}
}, movie.name = 'irl_pyramid.gif', interval = 0.2, ani.width = 700, ani.height = 600)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment