gganimate extends the grammar of graphics as implemented by ggplot2 to include the description of animation. It does this by providing a range of new grammar classes that can be added to the plot object in order to customise how it should change with time.

library(ggplot2)
library(gganimate)

Animate a qualitative variable

Here we take a simple boxplot of fuel consumption as a function of cylinders and lets it transition between the number of gears available in the cars:

head(mtcars)
##                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
## Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
## Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
## Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
## Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
## Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
## Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
# ggplot code
p = ggplot(mtcars, aes(factor(cyl), mpg)) + 
  geom_boxplot()

# Here comes the gganimate code
ap = p +  
  transition_states(
    gear,
    transition_length = 2,
    state_length = 1
  ) +
  enter_fade() + 
  exit_shrink() +
  ease_aes('sine-in-out') + 
  labs(title = 'Fuel consumption for {closest_state} gears', x = 'cyl')

# gif output
gif_cars = animate(ap)
gif_cars

# Video output
vp_cars = animate(ap, renderer = av_renderer())
vp_cars

Animate a quantitative variable

library(gapminder)

p = ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
  geom_point(alpha = 0.7, show.legend = FALSE) +
  scale_colour_manual(values = country_colors) +
  scale_size(range = c(2, 12)) +
  scale_x_log10() +
  facet_wrap(~continent)

# Here comes the gganimate specific bits
ap = p +
  labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') +
  transition_time(year) +
  ease_aes('linear') +
  shadow_wake(0.25, wrap = FALSE)

# gif output
gif_gap = animate(ap)
gif_gap

# Video output
vp_gap = animate(ap, renderer = av_renderer())
vp_gap

Let’s make a focus on the African continent:

library(dplyr)

p = gapminder %>% 
  filter(continent == "Africa") %>%
  ggplot(aes(gdpPercap, lifeExp, size = pop, colour = country)) +
  geom_point(alpha = 0.5, show.legend = FALSE) +
  scale_colour_manual(values = country_colors) +
  scale_size(range = c(2, 20)) +
  scale_x_log10() +
  theme_minimal()

# Here comes the gganimate specific bits
ap = p +  
  labs(title = 'Year: {frame_time}', x = 'GDP per capita (log)', y = 'life expectancy') +
  transition_time(year) +
  ease_aes('linear') +
  shadow_wake(0.20, wrap = FALSE)

# gif output
gif_gap2 = animate(ap)
gif_gap2


# Video output
vp_gap2 = animate(ap, renderer = av_renderer())
vp_gap2