Created
May 30, 2016 14:39
-
-
Save walkerke/bb891e729e76c5a68bde719f4b0db516 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(idbr) | |
library(dplyr) | |
library(ggplot2) | |
library(tidyr) | |
library(countrycode) | |
library(gganimate) | |
library(tweenr) | |
ctrys <- countrycode(c('South Africa', 'Botswana', 'Lesotho', 'Namibia', 'Zimbabwe', 'Swaziland'), | |
'country.name', 'fips104') | |
idb_api_key("Your API key here") | |
full <- idb5(country = ctrys, year = 1985:2016, | |
variables = c('E0_F', 'E0_M'), country_name = TRUE) | |
df2 <- full %>% | |
mutate(diff = E0_F - E0_M, ease = 'cubic-in-out') %>% | |
select(-FIPS) %>% | |
rename(Male = E0_M, Female = E0_F) | |
dft <- tween_elements(df2, time = 'time', group = 'NAME', ease = 'ease', | |
nframes = 500) | |
dft <- dft %>% | |
gather(Sex, value, Male, Female, -diff, -.group) | |
g <- ggplot() + | |
geom_point(data = dft, aes(x = value, y = .group, color = Sex, frame = .frame), | |
size = 14) + | |
scale_color_manual(values = c('darkred', 'navy')) + | |
geom_text(data = dft, aes(x = value, y = .group, frame = .frame, | |
label = as.character(round(dft$value, 1))), | |
color = 'white', fontface = 'bold') + | |
geom_text(data = dft, aes(x = 68.5, y = 1.5, frame = .frame, | |
label = round(dft$time, 0)), color = 'black', size = 12) + | |
theme_minimal(base_size = 16) + | |
theme(panel.grid.major.x = element_blank(), | |
panel.grid.minor.x = element_blank()) + | |
labs(y = '', | |
x = '', | |
caption = 'Data source: US Census Bureau IDB via the idbr R package', | |
title = 'Life expectancy at birth in southern Africa, 1985-2016') | |
gg_animate(g, interval = 0.05, ani.width = 800, ani.height = 700, title_frame = FALSE) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment