Animate Your Plots with gganimate


The gganimate package in R is an extension of the ggplot2 package, designed to create animated visualizations.
This post showcases the key features of gganimate and provides a set of animated graph examples using the package.

Documentation

{gganimate}

Quick start


The gganimate package in R is an extension of the ggplot2 package, designed to create animated and interactive visualizations.

It offers a set of grammar extensions that make it easy to specify animations in a declarative manner.

✍️ author β†’ Thomas Lin Pedersen

πŸ“˜ documentation β†’ gganimate.com

⭐️ more than 2000 stars on github

Installation


To get started with gganimate, you can install it directly from CRAN using the install.packages function:

install.packages("gganimate")

Basic usage


The gganimate package extends the grammar of graphics to include the description of animation. You start with a regular ggplot2 plot and add animation-specific layers to it.

Here’s a basic example where the year variable is used to animate the plot:

library(ggplot2)
library(gganimate)
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() +
  labs(title = "Year: {frame_time}", x = "GDP per capita", y = "life expectancy")

anim <- p + transition_time(year) +
  ease_aes("linear")

anim_save("../img/graph/gganimate-1.gif", anim)

Key features



β†’ Transitions

Transitions allow you to animate changes in your data over time or between different states.

This animation transitions between different gears (3, 4, and 5). The transition_states() function creates smooth transitions between these discrete states. Points fade in and out as they enter or exit each state.

library(ggplot2)
library(gganimate)

# Create a basic scatter plot
p <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
  geom_point(size = 3) +
  labs(
    title = "Car Weight vs MPG",
    subtitle = "Gear: {closest_state}",
    x = "Weight (1000 lbs)", y = "Miles per Gallon"
  )

# Add animation
anim <- p +
  transition_states(gear,
    transition_length = 2,
    state_length = 1
  ) +
  enter_fade() +
  exit_fade()

anim_save("../img/graph/gganimate-2.gif", anim)


β†’ Tweening

Tweening interpolates between different aesthetic values to create smooth animations over continuous variables.

This animation shows how life expectancy, GDP per capita, and population have changed over time for different countries. The transition_time() function creates a smooth animation over the years, with the points moving to their new positions each year.

library(ggplot2)
library(gganimate)
library(gapminder)

# Create a basic scatter plot
p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent)) +
  geom_point(alpha = 0.7) +
  scale_color_viridis_d() +
  scale_size(range = c(2, 12)) +
  scale_x_log10() +
  labs(
    title = "Year: {frame_time}",
    x = "GDP per capita",
    y = "Life expectancy"
  )

# Add animation
anim <- p +
  transition_time(year) +
  ease_aes("linear")

anim_save("../img/graph/gganimate-3.gif", anim)


β†’ Enter and Exit

You can control how data points appear and disappear during transitions.

This animation shows the average MPG for cars with different numbers of cylinders. The enter_grow() function makes new bars grow from the bottom, while exit_shrink() makes disappearing bars shrink down.

library(ggplot2)
library(gganimate)
library(dplyr)

# Prepare data
data <- mtcars %>%
  mutate(cyl = factor(cyl)) %>%
  group_by(cyl) %>%
  summarize(mpg = mean(mpg))

# Create a basic bar plot
p <- ggplot(data, aes(x = cyl, y = mpg, fill = cyl)) +
  geom_col() +
  labs(
    title = "Average MPG by Number of Cylinders",
    subtitle = "Showing: {closest_state}",
    x = "Number of Cylinders",
    y = "Average Miles per Gallon"
  )

# Add animation
anim <- p +
  transition_states(cyl) +
  enter_grow() +
  exit_shrink()

anim_save("../img/graph/gganimate-4.gif", anim)





❀️ 10 best R tricks ❀️

πŸ‘‹ After crafting hundreds of R charts over 12 years, I've distilled my top 10 tips and tricks. Receive them via email! One insight per day for the next 10 days! πŸ”₯