gganimate: Create Animations with ggplot2


The gganimate package is an extension to ggplot2 for creating an animated plot. It provides a supplementary aesthetic called frame, just like x, y, size, color, or so on. Thus, a variable in your data can be mapped to frame just as others are mapped to x or y.

Install

if(!require(devtools)) install.packages("devtools")
devtools::install_github("dgrtwo/gganimate")

Demo data sets

We’ll use the gapminder data set available in the package of the same name.

To install gapminder, type this:

install.packages("gapminder")

Inspect the data set:

library(gapminder)
head(gapminder)
##       country continent year lifeExp      pop gdpPercap
## 1 Afghanistan      Asia 1952    28.8  8425333       779
## 2 Afghanistan      Asia 1957    30.3  9240934       821
## 3 Afghanistan      Asia 1962    32.0 10267083       853
## 4 Afghanistan      Asia 1967    34.0 11537966       836
## 5 Afghanistan      Asia 1972    36.1 13079460       740
## 6 Afghanistan      Asia 1977    38.4 14880372       786

Simple animation

  • Plot the variable lifeExp (life expectancy at birth) by the variable gdpPercap (GDP per capita).
  • Make animation by year using the aesthetic frame = year.
# Load required package
library(gapminder)
library(ggplot2)
library(gganimate)
# Basic scatter plot
mapping <- aes(x = gdpPercap, y = lifeExp, 
               size = pop, color = continent,
               frame = year) 
p <- ggplot(gapminder, mapping = mapping) +
  geom_point() +
  scale_x_log10()
# Animate
gganimate(p)

Simple animation

  • To animate across continent, use frame = continent.
  • For faster animation use the option interval, for example interval = 0.2

Save the animation

Allowed format: an GIF, video, or an animated webpage.

gganimate(p, "output.gif")
gganimate(p, "output.mp4")
gganimate(p, "output.swf")
gganimate(p, "output.html")

System requirement: ffmpeg and ImageMagick drivers should be installed on your computer.

Customize

  • Animate some of the plot layers by highlighting particular points:
p2 <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop)) +
  geom_point() +
  geom_point(aes(frame = year), color = "red") +
  scale_x_log10()
gganimate(p2)

customize animation

  • Cumulative layer using the aesthetic cumulative = TRUE.
p3 <- ggplot(gapminder, aes(gdpPercap, lifeExp, frame = year)) +
  geom_path(aes(cumulative = TRUE, group = country)) +
  scale_x_log10() +
  facet_wrap(~continent)
gganimate(p3)

cumulative layers