In this workshop, we’ll practice some skills for creating animated graphics with ggplot2 and gganimate, plus some other cool things.

Note: We won’t be doing all of these examples in the workshop, but they’re here for you to explore.

Visit and fork the workshop repo on github for information and data.

Packages required:

Get the development version of gganimate:

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

An overview of gganimate terms

gganimate is an awesome new (and growing) package for intuitive graphics animation by Thomas Lin Pedersen (https://github.com/thomasp85/gganimate).

Some important terms to get us started:

My three pieces of advice for getting started (from a gganimate beginner)

library(tidyverse)
library(gganimate)
library(ggrepel)
library(ggridges)

1. Getting started: Channel Island Fox population on Santa Rosa Island

  1. Data (ci_fox_pop.csv): Friends of the Island Fox (http://www1.islandfox.org/2014/)
# Get data:
ci_fox_pop <- read_csv("ci_fox_pop.csv")

# Gather it:
fox <- ci_fox_pop %>% 
  gather(island, pop, san_miguel:san_nicolas)

# Make a static plot frst! 
ggplot(fox, aes(x = year, y = pop)) +
  geom_point(size = 3, aes(color = island)) +
  theme_dark() +
  scale_colour_manual(values = c("white", "yellow","orange","magenta", "aquamarine","olivedrab1")) +
  labs(x = "Year", y = "Fox Population", title = "Channel Island Fox Recovery") +
  scale_y_continuous(expand = c(0,0), limits = c(0,2000)) +
  scale_x_continuous(expand = c(0,0), limits = c(1994, 2016)) +
  facet_wrap(~year)# yes, this makes no sense - but this is what we want. All of the different states are plotting separately. That's good! We're going to combine them using gganimate transitions. 

  1. Now let’s make an animated version using transition_states:

From: https://rdrr.io/github/dgrtwo/gganimate/man/transition_states.html: “[transition_states] splits your data into multiple states based on the levels in a given column, much like ggplot2::facet_wrap() splits up the data in multiple panels. It then tweens (interpolates) between the defined states and pauses at each state.”

# Make an animated version (remove facet_wrap, instead add animation) - 30 seconds

ggplot(fox, aes(x = year, y = pop)) +
  geom_point(size = 3, aes(color = island)) +
  theme_dark() +
  scale_colour_manual(values = c("white", "yellow","orange","magenta", "aquamarine","olivedrab1")) +
  labs(x = "Year", y = "Fox Population", title = "Channel Island Fox Recovery") +
  scale_y_continuous(expand = c(0,0), limits = c(0,2000)) +
  scale_x_continuous(expand = c(0,0), limits = c(1994, 2016)) +
  transition_states(states = year, transition_length = 1, state_length = 1, wrap = FALSE)

  1. Changing ease functions (ease_aes) between states, and adding a shadow_wake

A fun thing to explore while rendering: https://easings.net/

ggplot(fox, aes(x = year, y = pop)) +
  geom_point(size = 3, aes(color = island)) +
  theme_dark() +
  scale_colour_manual(values = c("white", "yellow","orange","magenta", "aquamarine","olivedrab1")) +
  labs(x = "Year", y = "Fox Population", title = "Channel Island Fox Recovery") +
  scale_y_continuous(expand = c(0,0), limits = c(0,2000)) +
  scale_x_continuous(expand = c(0,0), limits = c(1994, 2016)) +
  transition_states(states = year, transition_length = 1, state_length = 1, wrap = FALSE) +
  ease_aes('cubic-in-out') +
  shadow_wake(wake_length = 0.2) 

  1. Use shadow_mark to leave previous frame points behind!
# Also try shadow_mark to leave a point:

ggplot(fox, aes(x = year, y = pop)) +
  geom_point(size = 3, aes(color = island)) +
  theme_dark() +
  scale_colour_manual(values = c("white", "yellow","orange","magenta", "aquamarine","olivedrab1")) +
  labs(x = "Year", y = "Fox Population", title = "Channel Island Fox Recovery") +
  scale_y_continuous(expand = c(0,0), limits = c(0,2000)) +
  scale_x_continuous(expand = c(0,0), limits = c(1994, 2016)) +
  transition_states(states = year, transition_length = 1, state_length = 1, wrap = FALSE) +
  ease_aes('cubic-in-out') +
  shadow_mark()

  1. Create an animated line graph of fox populations with transition_reveal():

From Thomas Lin Pedersen (https://github.com/thomasp85/gganimate/wiki/Temperature-time-series): “We use transition_reveal() to allow the lines to gradually be build up. transition_reveal() knows to only keep old data for path and polygon type layers which means that our segment, point, and text layers only appears as single data points in each frame.”

# And now with a line graph (transition_reveal):

ggplot(fox, aes(x = year, y = pop)) +
  geom_line(size = 1, aes(color = island)) +
  theme_dark() +
  scale_colour_manual(values = c("white", "yellow","orange","magenta", "aquamarine","olivedrab1")) +
  labs(x = "Year", y = "Fox Population", title = "Channel Island Fox Recovery") +
  scale_y_continuous(expand = c(0,0), limits = c(0,2000)) +
  scale_x_continuous(expand = c(0,0), limits = c(1994, 2016)) +
  transition_reveal(id = island, along = year) + # really wants two things...
  ease_aes('quadratic-in-out')

  1. Add labels to the animated line graph of fox populations
ggplot(fox, aes(x = year, y = pop, group = island)) +
  geom_line(size = 1, aes(color = island)) +
  geom_segment(aes(xend = 2016, yend = pop), linetype = 2, colour = 'grey') + 
  geom_label(aes(x = 2016.5, label = island, fill = island), hjust = 0, color = "black") + 
  theme_dark() +
  theme(legend.position = "none") +
  scale_color_manual(values = c("white", "yellow","orange","magenta", "aquamarine","olivedrab1")) +
  scale_fill_manual(values = c("white", "yellow","orange","magenta", "aquamarine","olivedrab1")) +
  labs(x = "Year", y = "Fox Population", title = "Channel Island Fox Recovery\nYear: {frame_along}") +
  scale_y_continuous(expand = c(0,0), limits = c(0,2000)) +
  scale_x_continuous(expand = c(0,0), limits = c(1994, 2022)) +
  transition_reveal(id = island, along = year) + # really wants two things...
  ease_aes('quadratic-in-out')

2. Star Wars characters: transition_manual, transition_layers, ggrepel, rendering gifs to send to all your friends and family

  1. The ‘starwars’ dataset exists in dplyr (part of the tidvyerse), with data from the Star Wars API (https://swapi.co/). First, look at the data.
View(starwars)
  1. Filter to only include data for species: human, droid, wookiee, ewok. Relevel species with forcats’ fct_relevel
sw <- starwars %>% 
  filter(species == "Human" | species == "Droid" | species == "Wookiee" | species == "Ewok") %>% 
  mutate(species = factor(species))

sw$species <- fct_relevel(sw$species, "Ewok","Droid","Human","Wookiee")
  1. Remember the first step I recommend for gganimate: make a static version first, with different states (in this case, species) separated using facet_wrap:

Another thing included here:

geom_text_repel (from ggrepel) - for “repulsive textual annotations” (seriously, see the documentation with ?geom_text_repel)

# Static version: 

ggplot(sw, aes(x = height, y = mass, label = name)) +
  geom_point(aes(color = species)) + 
  geom_text_repel(size = 2, segment.color = "gray60", segment.size = 0.2) +
  scale_color_manual(values = c("orange","navyblue","magenta","forestgreen")) +
  theme_bw()# Yeah, looks bad but this is what we want! 

  1. Now that the static version is working, make an animated version using transition_manual

From https://rdrr.io/github/dgrtwo/gganimate/man/transition_manual.html: “[transition_manual] allows you to map a variable in your data to a specific frame in the animation. No tweening of data will be made and the number of frames in the animation will be decided by the number of levels in the frame variable.”

# Animated version (copied from above, minus facet_wrap): 

sw_graph <- ggplot(sw, aes(x = height, y = mass, label = name)) +
  geom_point(aes(color = species), size = 3) + 
  labs(title = "Species: {current_frame}") +
  geom_text_repel(size = 3, segment.color = "gray60", segment.size = 0.2) + 
  scale_color_manual(values = c("orange","navyblue","magenta","forestgreen")) +
  theme_bw() +
  transition_manual(frames = species) # No tweening! That makes sense if you don't have a logical path between states. Just want discrete frames that follow each other. Note: There is an argument 'cumulative = TRUE' that seems to be under development with some issues in newer versions...check back later to see if working. 

sw_graph
## nframes and fps adjusted to match transition

# Rendering so you can send this to all your friends:
# animate(sw_graph, nframes = 4, renderer = gifski_renderer("sw_graph.gif"))
  1. Use transition_layers to animate geoms on top of each other

From gganimate documentation: “[transition_layers] gradually adds layers to the plot in the order they have been defined. By default prior layers are kept for the remainder of the animation, but they can also be set to be removed as the next layer enters.”

Try using different enter_ options to change how the layers appear (e.g. enter_fade()). Note: exit_ options also exist, but since the layers are NOT exiting, it’s NA here. See the second example for an exit_ example.

ggplot(sw, aes(x = height, y = mass, label = name)) +
  geom_point(color = "gray50", size = 4) +
  geom_smooth(method = "lm", se = FALSE, color = "black", lty = 5, size = 0.5) +
  geom_smooth(method = "lm", se = TRUE, color = "NA") +
  scale_color_manual(values = c("orange","navyblue","magenta","forestgreen")) +
  theme_bw() +
  transition_layers(layer_length = 1, transition_length = 2) +
  enter_fade()

  1. An transition_layers example with previous layers NOT retained (and exit_ updated) - here, height by planet (Tatooine or Naboo) ignoring all other variables
sw_planets <- starwars %>% 
  filter(homeworld == "Tatooine" | homeworld == "Naboo")

ggplot(sw_planets, aes(x = homeworld, y = height)) +
  geom_boxplot(aes(fill = homeworld)) +
  geom_jitter(aes(color = homeworld), width = 0.1) +
  geom_violin(aes(color = homeworld, fill = homeworld)) +
  theme_bw() +
  transition_layers(layer_length = 1, transition_length = 2, keep_layers = FALSE) +
  enter_fade() +
  exit_fade()

3. Abalone + ridge plot + transition_states (Joy Division meets action figures)

**Data:** Accessed from UCI Machine Learning Repository (https://archive.ics.uci.edu/ml/datasets/abalone)

Warwick J Nash, Tracy L Sellers, Simon R Talbot, Andrew J Cawthorn and Wes B Ford (1994), “The Population Biology of Abalone (Haliotis species) in Tasmania. I. Blacklip Abalone (H. rubra) from the North Coast and Islands of Bass Strait”, Sea Fisheries Division, Technical Report No. 48 (ISSN 1034-3288)

Relevant info:

Animated abalone ridge plot with density plots separated by sex:

abalone <- read_csv("abalone.csv") %>% 
  filter(sex == "M" | sex == "F" | sex == "I") %>% 
  filter(age_years > 4 & age_years < 25) %>% 
  mutate(sex = fct_relevel(as.factor(sex), "I","F","M"))

ab_graph <- ggplot(abalone, aes(x = length_mm, y = age_years, fill = sex)) +
  geom_density_ridges(alpha = 0.5, color = "white") +
  scale_fill_manual(values = c("purple","blue","cyan")) +
  theme_minimal() +
  labs(x = "Shell Length (mm)", y = "Abalone Age (years)") +
  transition_states(age_years, transition_length = 1, state_length = 1) +
  shadow_mark()

ab_graph

# animate(ab_graph, nframes = 100, renderer = gifski_renderer("ab_graph.gif"))

A few more random examples

ggplot(abalone, aes(x = length_mm, y = diameter_mm)) +
  geom_point(aes(color = age_years, size = height_mm)) +
  labs(title = "Abalone age: {closest_state} years", x = "Length (") +
  theme_dark()+
  scale_color_gradientn(colors = c("magenta","orange","yellow","white")) +
  transition_states(age_years, transition_length = 1, state_length = 2) +
  enter_fade()+
  exit_fade() +
  shadow_mark()

And another abalone example…

# Another one: 

ggplot(abalone, aes(x = age_years, y = diameter_mm)) +
  geom_point(aes(size = length_mm, color = diameter_mm)) +
  scale_color_gradient(low = "magenta", high = "yellow") +
  theme_dark()+
  transition_states(age_years, transition_length = 2, state_length = 3) +
  shadow_mark() +
  enter_fade() +
  ease_aes('back-in')

The following examples use dataset ‘ChickWeight’ in base R. Use ?ChickWeight for more information.

# Animated column plot:

ggplot(ChickWeight, aes(x = Chick, y = weight)) +
  geom_col(aes(fill = Diet)) +
  labs(title = "Age (days): {closest_state}") +
  scale_fill_manual(values = c("yellow","orange","coral","magenta")) +
  scale_y_continuous(expand = c(0,0)) +
  theme_dark() +
  transition_states(Time, transition_length = 3, state_length = 1)

# Find mean weight by time for each feed type
mean_wt <- ChickWeight %>% 
  group_by(Diet, Time) %>% 
  summarize(
    mean_wt = mean(weight)
  )

# Animated line plot

ggplot(mean_wt, aes(x = Time, y = mean_wt, label = Diet)) +
  geom_line(aes(color = Diet)) +
  geom_text(nudge_x = 0.2, nudge_y = 5) +
  theme_light() +
  scale_color_manual(values = c("dodgerblue","green3","purple","orange")) +
  transition_reveal(Diet, Time)