Inspired by Hans Rosling’s TED Talk: The best stats you’ve ever seen.

The code is taken nearly verbatim from the gganimate example.

Install packages

install.packages(c("devtools", "dplyr", "ggplot2", "readr"))
library(devtools)
devtools::install_github("dgrtwo/gganimate")

Note that gganimate requires ImageMagick. To install it, use Homebrew on a Mac and Linuxbrew or apt-get or yum on Linux:

brew install imagemagick
sudo apt-get install imagemagick
sudo yum install imagemagick

Load packages

library(dplyr)
library(gganimate)
library(ggplot2)
library(readr)

Read the Gapminder data

gapminder <- read_tsv("gapminderDataFiveYear.tsv")
glimpse(gapminder)
## Observations: 1,704
## Variables: 6
## $ country   (chr) "Afghanistan", "Afghanistan", "Afghanistan", "Afghan...
## $ year      (int) 1952, 1957, 1962, 1967, 1972, 1977, 1982, 1987, 1992...
## $ pop       (dbl) 8425333, 9240934, 10267083, 11537966, 13079460, 1488...
## $ continent (chr) "Asia", "Asia", "Asia", "Asia", "Asia", "Asia", "Asi...
## $ lifeExp   (dbl) 28.801, 30.332, 31.997, 34.020, 36.088, 38.438, 39.8...
## $ gdpPercap (dbl) 779.4453, 820.8530, 853.1007, 836.1971, 739.9811, 78...

Plot the Gapminder data

gapminder_plot <- ggplot(gapminder) +
    aes(x = gdpPercap, y = lifeExp, colour = continent, size = pop,
        frame = year) +
    geom_point(alpha = 0.4) +
    scale_x_log10()
gapminder_plot

Animate the Gapminder data

gg_animate(gapminder_plot, filename = "gapminder-gganimate.gif")

Animated Gapminder figure