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)