Daily news about using open source R for big data analysis, predictive modeling, data science, and visualization since 2008

May 23, 2017

Create smooth animations in R with the tweenr package

There are several tools available in R for creating animations (movies) from statistical graphics. The animation package by Yihui Xie will create an animated GIF or video file, using a series of R charts you generate as the frames. And the gganimate package by David Robinson is an extension to ggplot2 that will create a movie from charts created using the ggplot2 syntax: in much the same way that you can create multiple panels using faceting, you can instead create an animation with multiple frames.

But from a storytelling perspective, such animations can sometimes seem rather disjointed. For example, here's the example (from the gganimate documentation) of crating an animated bubble chart from the gapminder data. (NOTE: to use the gganimate package, you will need to install ImageMagick. On Windows, be sure to select the "install legacy utilities" option during install: gganimate requires the "convert" utility to operate.)

The data are all there, but the presentation lacks the style of the original Gapminder presentation, which smoothly moved the bubbles between the known data points separated by five-year intervals. You can achieve a similar effect in R by using the tweenr package, available on CRAN. The tweenr package doesn't actually perform any animation itself; rather, it calculates smooth interpolations between data points to create new rows in the data which can be used as frames in the animation created by the gganimate package. Here's the same chart, with data processed by tweenr:

To achieve this affect, I used the tween_elements function to augment the original gapminder data set to make 300 frames of animation, smoothing the transitions of Life Expectancy, GDP per capita, and population, and then animating the result with gganimate. This snimation tutorial by Peter Aldhous was most helpful in developing the code shown below.

For another nice example using the tweenr package, check out this blog post by Jake Thompson replicating the Datasaurus Dozen as an animation in R. (Note that every frame of the animation has almost the exact same set of summary statistics.)

For more on the tweenr package, check out its homepage on Github from its author, Thomas Lin Pedersen.