Setup

To get started, load the tidyverse (or just ggplot2) and gganimate.

You can’t install gganimate from cran yet, so for now, you’ll need:

# install.packages('devtools') devtools::install_github('thomasp85/gganimate')

library(tidyverse)
library(gganimate)

Basics of gganimate

Here’s an canned example using the mtcars dataset.

This uses states (i.e. categorical variables) for the transition.

library(ggplot2)
library(gganimate)

ggplot(mtcars, aes(factor(cyl), mpg, color = as.factor(cyl))) + 
  geom_boxplot() + 
  # Here comes the gganimate code
  transition_states(
    gear,
    transition_length = 2,
    state_length = 1
  ) +
  enter_fade() + 
  exit_shrink() +
  ease_aes('sine-in-out')

Here’s another example looking at toothgrowth in guinea pigs fed either orange juice (OJ) or vitamin C supplement (VC) at increasing doses. This uses time instead of states for the transition.

ggplot(ToothGrowth, aes(x = supp, y = len, color = supp)) + 
      geom_boxplot() +
      labs(title = 'Dose: {closest_state} mg', x = 'Supplement', y = 'Tooth Length') +
      transition_states(dose, transition_length = 1, state_length = 1) +
      # ease_aes('linear') +
      theme(text = element_text(size=18, face='bold'))