gganimate: How to Create Plots with Beautiful Animation in R



gganimate: How to Create Plots with Beautiful Animation in R

This article describes how to create animation in R using the gganimate R package.

gganimate is an extension of the ggplot2 package for creating animated ggplots. It provides a range of new functionality that can be added to the plot object in order to customize how it should change with time.

Key features of gganimate:

  • transitions: you want your data to change
  • views: you want your viewpoint to change
  • shadows: you want the animation to have memory

Contents:

Prerequisites

gganimate stable version is available on CRAN and can be installed with install.packages('gganimate'). The latest development version can be installed as follow: devtools::install_github('thomasp85/gganimate').

Note that, in this tutorial, we used the latest developmental version.

Load required packages and set the default ggplot2 theme to theme_bw():

library(ggplot2)
library(gganimate)
theme_set(theme_bw())

Demo dataset

library(gapminder)
head(gapminder)
## # A tibble: 6 x 6
##   country     continent  year lifeExp      pop gdpPercap
##   <fct>       <fct>     <int>   <dbl>    <int>     <dbl>
## 1 Afghanistan Asia       1952    28.8  8425333      779.
## 2 Afghanistan Asia       1957    30.3  9240934      821.
## 3 Afghanistan Asia       1962    32.0 10267083      853.
## 4 Afghanistan Asia       1967    34.0 11537966      836.
## 5 Afghanistan Asia       1972    36.1 13079460      740.
## 6 Afghanistan Asia       1977    38.4 14880372      786.

Static plot

p <- ggplot(
  gapminder, 
  aes(x = gdpPercap, y=lifeExp, size = pop, colour = country)
  ) +
  geom_point(show.legend = FALSE, alpha = 0.7) +
  scale_color_viridis_d() +
  scale_size(range = c(2, 12)) +
  scale_x_log10() +
  labs(x = "GDP per capita", y = "Life expectancy")
p

Transition through distinct states in time

Basics

Key R function: transition_time(). The transition length between the states will be set to correspond to the actual time difference between them.

Label variables: frame_time. Gives the time that the current frame corresponds to.

p + transition_time(year) +
  labs(title = "Year: {frame_time}")

Transition time

Create facets by continent:

p + facet_wrap(~continent) +
  transition_time(year) +
  labs(title = "Year: {frame_time}")

Transition time, facet by continents

Let the view follow the data in each frame

p + transition_time(year) +
  labs(title = "Year: {frame_time}") +
  view_follow(fixed_y = TRUE)

View follow

Show preceding frames with gradual falloff

This shadow is meant to draw a small wake after data by showing the latest frames up to the current. You can choose to gradually diminish the size and/or opacity of the shadow. The length of the wake is not given in absolute frames as that would make the animation susceptible to changes in the framerate. Instead it is given as a proportion of the total length of the animation.

p + transition_time(year) +
  labs(title = "Year: {frame_time}") +
  shadow_wake(wake_length = 0.1, alpha = FALSE)

Shadow Wake

Show the original data as background marks

This shadow lets you show the raw data behind the current frame. Both past and/or future raw data can be shown and styled as you want.

p + transition_time(year) +
  labs(title = "Year: {frame_time}") +
  shadow_mark(alpha = 0.3, size = 0.5)

Shadow Mark

Reveal data along a given dimension

This transition allows you to let data gradually appear, based on a given time dimension.

Static plot

p <- ggplot(
  airquality,
  aes(Day, Temp, group = Month, color = factor(Month))
  ) +
  geom_line() +
  scale_color_viridis_d() +
  labs(x = "Day of Month", y = "Temperature") +
  theme(legend.position = "top")
p

Let data gradually appear

  • Reveal by day (x-axis)
p + transition_reveal(Day)

Let data gradually appear

  • Show points:
p + 
  geom_point() +
  transition_reveal(Day)

Let data gradually appear

  • Points can be kept by giving them a unique group:
p + 
  geom_point(aes(group = seq_along(Day))) +
  transition_reveal(Day)

Let data gradually appear, keep points

Transition between several distinct stages of the data

Data preparation:

library(dplyr)
mean.temp <- airquality %>%
  group_by(Month) %>%
  summarise(Temp = mean(Temp))
mean.temp
## # A tibble: 5 x 2
##   Month  Temp
##   <int> <dbl>
## 1     5  65.5
## 2     6  79.1
## 3     7  83.9
## 4     8  84.0
## 5     9  76.9

Create a bar plot of mean temperature:

p <- ggplot(mean.temp, aes(Month, Temp, fill = Temp)) +
  geom_col() +
  scale_fill_distiller(palette = "Reds", direction = 1) +
  theme_minimal() +
  theme(
    panel.grid = element_blank(),
    panel.grid.major.y = element_line(color = "white"),
    panel.ontop = TRUE
  )
p

  • transition_states():
p + transition_states(Month, wrap = FALSE) +
  shadow_mark()

transition states

  • enter_grow() + enter_fade()
p + transition_states(Month, wrap = FALSE) +
  shadow_mark() +
  enter_grow() +
  enter_fade()

Save animation

If you need to save the animation for later use you can use the anim_save() function.

It works much like ggsave() from ggplot2 and automatically grabs the last rendered animation if you do not specify one directly.

Example of usage:





Comments ( 12 )

  • Transition_reveal

    nice write up!!! thanks

    had a query.. any insight how do I fade the other lines when I reveal current line… in transition_reveal

    this will give clear visibility to transition_reveal in case too many are in perpective

    I hope I could clearly give the problem statement

  • Draga

    This is beautiful! I love it! I want to use it but in my data set.
    May I ask you to provide an example of the anim_save ( ) function, please, since the examples I found do not work for me. Thank you!

    • Tiago

      Hi Draga,

      I’ve been using the function animate () in order to save the output.

      Example:

      animate(p, nframes=x, height=y, width=w, res=z, gifski_renderer(“my.gif”))

      So in this case I’m specifying the number of frames, height, width and also the resolution of the output.

      I hope it helps
      Cheers

      • Draga

        Dear Tiago,

        Many thanks for your kind answer. It works. I would like to know is it possible to change the color for one specific country, for example, red color only for China (and how)? I would appreciate your answer. Many thanks in advance.

      • Draga

        I missed to let you know that I would like to change the color only for China for your second chart (Transition through distinct states in time). Thank you.

  • Chris W

    How would you animate showing a years worth of monthly date throughout 20 years, scrolling right to left, e.g. Jan to Dec 2000, then Feb 2000 to Jan 2001 etc. Each frame would show each of the twelve months. So you would see the data floating right to left throughout the months and years.

  • Danhrogers

    Hi, this is fantastic stuff. Unfortunately, my efforts fall down repeatedly when I run various examples from this and other websites. I always get an Error: Don’t know how to add transition_states (…or transition_dates, etc. ) to a plot. I’ve downloaded “Fix version check to match the ggplot2 hotfix” but don’t know how to incorporate it into the gganimate code. I’m a complete novice so please bare with me :/

  • Kun Thaung

    Very awesome topic for me. Thank for this site and share an important technic for learner like me.

  • Kun Thaung

    we got error with along data to be provided:
    with this code
    p + geom_point() + transition_reveal(Day)

    I include it with transition_reveal(Month,Day). It work well.

  • Sylvan

    Hi, great explanation,

    how do you change the size and fps of the gif? mine is very small (about 1/4 of the window) and running quite fast.

    Thanks

  • Ankit

    The article is very useful for me.

Post a Reply