Animation plot with gganimate

Create plots with animations using gganimate package in Rstudio!

Leah Nguyen
5 min readMar 29, 2022

Data visualization is critical to any data science project because it enables effective data storytelling through graphs and plots. Additionally, data visualization with R is a necessary skill to develop in order to communicate effectively with stakeholders.

Concentrating on a statistical chart, on the other hand, is difficult in most cases, and you have no control over the pace at which the information is presented, particularly with time series analysis. The gganimate package extends ggplot, allowing us to create visually appealing data animations with only a few additional lines of code. Furthermore, we can customize and enhance the interactivity of your graphs. I will demonstrate how to further enhance these ggplot visualizations by animating them using the gganimate package in this report.

View my repository for this project at https://github.com/ndleah/gganimate

The Dataset

In this tutorial, I am using 3 R packages:

  • tidyverse — a collection of packages that coexist harmoniously.
  • gganimate — enables us to integrate animation into our plots.
  • ggtheme — generates ggplot2 themes and scales that mimic the appearance of plots.

As with creating a graph, the first step in creating animations in R gganimate is to ensure that our data is in a tidy shape. This implies the following:

  1. Each column must contain a variable.
  2. Each row should correspond to a single observation.
  3. Each cell should have a unique value.

In our case, we will use the gapminder dataset, as it is a classic dataset in the animation field.

The dataset contains 1704 observations and 6 variables and this dataset is loaded from thegapminder package.

These six columns include the following:

  • country — Country names
  • continent — Continent names
  • year — Date of data entry
  • lifeExp — Yearly life expectancy
  • pop — Year-by-year population count
  • gdpPercap — GDP per capita for the specified year

Data Visualization (with animation)

Creating a basic static plot

To begin creating our animation, we will create a static ggplot graph and save it to graph1. The purpose of the static graph is to present the data in an appealing manner and then create the animation on top of it.

# Make a ggplot, but add frame=year: one image per year
graph1 <- gapminder %>%
# plot the data with scatterplots
ggplot(aes(gdpPercap, lifeExp, size = pop, color = continent)) +
geom_point() +
# axis transformations
scale_x_log10() +
theme_bw()
graph1

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.

Transition through distinct states in time

Now you can incorporate the animation into a basic ggplot graph. Take note that when you run this code, the visual takes some time to render. This is because RStudio is creating a gif representation of your animated chart.

graph1_animation = graph1 +
transition_time(year) +
labs(subtitle = "Year: {frame_time}")
graph1_animation

We see the use of transition_time() in this example, which can be used with continuous variables such as year. It is not necessary to specify the transition and state lengths for this transition because the “transition variable” does so automatically. Titles also make use of string literal interpolation. gganimateallows you to specify variables to evaluate within titles, and various transitions provide various types of data to use.

Display preceding frames with a gradual decrease in size

By displaying the most recent frames up to the current, this shadow is intended to create a small wake after data. You can choose to gradually reduce the shadow’s size and/or opacity. The duration of the wake is not specified in absolute frames, as this would subject the animation to framerate changes. Rather than that, it is expressed as a percentage of the total duration of the animation.

graph1_animation <- graph1 +
transition_time(year) +
labs(subtitle = "Year: {frame_time}") +
shadow_wake(wake_length = 0.1, alpha = FALSE)
graph1_animation

Make the label more visible

With the animation, it’s more engaging to see how life expectancy has changed over time in different countries. However, as you can see, the date is included in the title, but it is omitted from the graph, which prevents the title from being used for other purposes.

That is why including the data on the same graph with an additional ggplot layer is much more visually appealing and impactful. This way, we can use any title we want, we can give the transition state any look and feel we want, and it will remain contained within the graph.

graph1_animation_2 <- graph1 +
geom_text(aes(x = min(gdpPercap), y = min(lifeExp), label = as.factor(year)) , hjust=-1.5, vjust = -0.2, alpha = 0.2, col = "gray", size = 20) +
transition_states(as.factor(year), state_length = 0)
#display the graph
graph1_animation_2

All of my code snippets in this article are available as follows:

Conclusions

Understanding how to create animations in R is not only simple but also extremely useful. If you want to create more impactful graphs and have the option of displaying them as animations, I strongly advise you to do so. However, animations are more beneficial.

In summary, whatever your line of work, I hope you enjoyed learning how to create animations in R using gganimate.

References

Faber, I. (2020, September 30). Animating your data visualizations like a boss using r. Medium. https://towardsdatascience.com/animating-your-data-visualizations-like-a-boss-using-r-f94ae20843e3.

gganimate. (n.d.). https://gganimate.com/reference/index.html.

Waniek, L. (2020, February 13). Animated plots using ggplot and gganimate. STATWORX. https://www.statworx.com/ch/blog/animated-plots-using-ggplot-and-gganimate/.

Hi friend, I’m Leah and I’m a data enthusiast! 👩‍💻 Follow me for more data contents or:

👉 Connect with me on LinkedIn: https://www.linkedin.com/in/ndleah/

👉 My GitHub: https://github.com/ndleah

👉 My Medium profile: https://medium.com/@ndleah

--

--