Skip to content

Instantly share code, notes, and snippets.

@fototo
Forked from walkerke/india_pyramid.R
Created April 5, 2016 14:21
Show Gist options
  • Save fototo/4f15d040a2f9ed9c0f0dfa0b5831efd9 to your computer and use it in GitHub Desktop.
Save fototo/4f15d040a2f9ed9c0f0dfa0b5831efd9 to your computer and use it in GitHub Desktop.
library(idbr)
library(ggplot2)
library(animation)
library(dplyr)
library(gganimate)
idb_api_key("Your Census API key goes here")
male <- idb1('IN', 2000:2050, sex = 'male') %>%
mutate(POP = POP * -1,
SEX = 'Male')
female <- idb1('IN', 2000:2050, sex = 'female') %>%
mutate(SEX = 'Female')
india <- rbind(male, female)
# Animate it with gganimate
g1 <- ggplot(india, aes(x = AGE, y = POP, fill = SEX, width = 1, frame = time)) +
coord_fixed() +
coord_flip() +
geom_bar(data = subset(india, SEX == "Female"), stat = "identity", position = 'identity') +
geom_bar(data = subset(india, SEX == "Male"), stat = "identity", position = 'identity') +
scale_y_continuous(breaks = seq(-10000000, 10000000, 5000000),
labels = c('10m', '5m', '0', '5m', '10m'),
limits = c(min(india$POP), max(india$POP))) +
theme_minimal(base_size = 14, base_family = "Lucida Sans") +
scale_fill_manual(values = c('#ffbb78', '#ff7f0e')) +
ggtitle('Population structure of India,') +
ylab('Population') +
xlab('Age') +
theme(legend.position = "bottom", legend.title = element_blank()) +
labs(caption = 'Data source: US Census Bureau IDB via the idbr R package') +
guides(fill = guide_legend(reverse = TRUE))
ani.options(interval = .1, ani.width = 700, ani.height = 600)
gg_animate(g1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment