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')
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:
state: a ‘phase’ that you could plot statically, but you want to create transitions between for different phases (years, species, countries, etc.) - these might be things that you would otherwise consider plotting in different facets. So make sure that you can plot these statically FIRST, then add transitions!
transition: How you want to shift from one state to another visually. These include things like: Will there be interpolation between states or frames? Ask yourself: does having a motion transition between things make sense? Would you put a line between them on a graph?
tweening: Interpolation between states to determine pathway function. Default is linear…but we can change that to make it a little more fun. Also keep in mind that this doesn’t always make sense!
ease_aes: Visually update the ‘look’ of transitions between states by setting a function. Elastic is a pretty fun one. Check display_ease() from tweenr to see options for in/out functions for tweening interpolation. Note that you can add ‘in’ or ‘out’ separately, or ‘in-out’ for symmetric function at interpolation endpoints.
enter and exit: How will things enter and exit WITHIN STATES at the beginning and end (fade, etc.)? Better to tween between discrete groups (vs. transition connected)
Make a static version first, ensuring that you can see all of your different states separately (and successfully), possibly using facet_wrap. Then…
Start simply, then build animation pieces.
Don’t do it just because you can, do it because it’s helps create an engaging visual that is scientifically sound AND benefits audience understanding AND looks awesome.
library(tidyverse)
library(gganimate)
library(ggrepel)
library(ggridges)
# 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.
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)
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)
# 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()
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')
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')
View(starwars)
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")
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!
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"))
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()
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()
**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"))
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)