Animated Plots with gganimate

By Kailas Venkitasubramanian in R

March 3, 2022

Line Plots

Let’s accomplish making line plots that snake across the axes. I love these because they closely draw people’s attention to the change occurring (usually over time).

First, you’ll need the following libraries loaded in R to do this exercise

Load the libraries

library(ggplot2)
library(gganimate)
library(babynames)
library(hrbrthemes)
library(tidyverse)
library(viridis)
library(ggthemr)

The babynames package is a dataset of all American baby names over time. Let’s use the dataset to extract five names that we want to use in the plot.

Prepare Data

don <- babynames %>% 
  filter(name %in% c("Ashley", "Patricia", "Helen", "Allison", "Katie")) %>%
  filter(sex=="F")

Plot and Animate

Let’s now plot how popular these five names have been across time. And let’s animate the change.

ggthemr('dust')
p <- don %>%
  ggplot( aes(x=year, y=n, group=name, color=name)) +
  geom_line() +
  geom_point() +
  scale_color_viridis(discrete = TRUE) +
  ggtitle("Popularity of American names in the previous 30 years") +
  ylab("Number of babies born") +
  transition_reveal(year)

animate(p, height = 600, width = 800)

Helen peaked in the 20s, Patricia in the 50s, and Ashley in the 80s-90s. Katie and Ashley both peaked in the 90s.

Other useful functions in the `gganimate' package

transition_*(): This function creates animation transitions based on the values of a particular variable. There are several variations of this function, including transition_time(), transition_states(), and transition_manual(), which allow you to animate based on time, discrete states, or custom values, respectively.

view_follow(): This function keeps the view of the plot centered on a particular point as it moves over time. This is particularly useful for visualizing changes in spatial data or maps.

ease_aes(): This function allows you to specify how a particular aesthetic should change over time. You can use it to create smooth or abrupt transitions, or to add special effects like bouncing or elastic motion.

shadow_mark(): This function creates a “shadow” of the plot that fades out over time, which can be useful for emphasizing the most recent data points or trends.

enter_*() and exit_*() functions: These functions control how new data points enter and old data points exit the plot. For example, you might use enter_fade() to smoothly fade in new data points, or exit_drift() to have old data points slowly drift off the screen.