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.
if(!require(devtools)) install.packages("devtools")
devtools::install_github("dgrtwo/gganimate")
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
# 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)

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.
p2 <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop)) +
geom_point() +
geom_point(aes(frame = year), color = "red") +
scale_x_log10()
gganimate(p2)

p3 <- ggplot(gapminder, aes(gdpPercap, lifeExp, frame = year)) +
geom_path(aes(cumulative = TRUE, group = country)) +
scale_x_log10() +
facet_wrap(~continent)
gganimate(p3)
