Skip to content

Instantly share code, notes, and snippets.

@walkerke
Created June 4, 2016 10:50
Show Gist options
  • Save walkerke/5ef209e2f596940ec54e2bd85be56775 to your computer and use it in GitHub Desktop.
Save walkerke/5ef209e2f596940ec54e2bd85be56775 to your computer and use it in GitHub Desktop.
library(idbr)
library(dplyr)
library(ggplot2)
library(tidyr)
library(countrycode)
library(gganimate)
library(tweenr)
ctrys <- countrycode(c('Russia', 'Ukraine', 'Belarus', 'Moldova', 'Georgia', 'Kazakhstan',
'Uzbekistan', 'Lithuania', 'Latvia', 'Estonia', 'Kyrgyzstan',
'Tajikistan', 'Turkmenistan', 'Armenia', 'Azerbaijan'),
'country.name', 'fips104')
idb_api_key("Your API key here")
full <- idb5(country = ctrys, year = 1989:2016,
variables = c('E0_F', 'E0_M'), country_name = TRUE)
tmp <- full %>%
filter(time == 1989) %>%
arrange(E0_F)
ord <- as.character(as.vector(tmp$NAME))
dft <- full %>%
mutate(diff = E0_F - E0_M, ease = 'cubic-in-out') %>%
select(-FIPS) %>%
rename(Male = E0_M, Female = E0_F) %>%
tween_elements(time = 'time', group = 'NAME', ease = 'ease',
nframes = 500) %>%
gather(Sex, value, Male, Female, -diff, -.group) %>%
mutate(.group = factor(.group, levels = ord))
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 = 80, y = 1.5, frame = .frame,
label = round(dft$time, 0)), color = 'black', size = 12) +
theme_minimal(base_size = 16, base_family = "Tahoma") +
theme(panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank()) +
labs(y = '',
x = '',
color = '',
caption = 'Data source: US Census Bureau IDB via the idbr R package; chart by @kyle_e_walker',
title = 'Life expectancy at birth in the former USSR, 1989-2016')
gg_animate(g, interval = 0.05, ani.width = 750, ani.height = 650, title_frame = FALSE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment