In this post, we will learn to make simple animation in R using gganimate package. gganimate R package is a powerful package to make animation using R.
gganimate extends the grammar of graphics as implemented by ggplot2 to include the description of animation. It does this by providing a range of new grammar classes that can be added to the plot object in order to customise how it should change with time.
Let us load the packages we need to make animation in R.
library(tidyverse) library(gganimate) library(gapminder) theme_set(theme_bw(16))
We will use gaopminder data to make the animation. More specifically, we will make a barplot animation of average life expectancy over time for each continent in the gapminder dataset.
Let us compute average life expectancy for each continetnt per year by using group_by() function and summarize() function.
df <- gapminder %>% group_by(continent, year) %>% summarize(mean_lifeExp=mean(lifeExp))
And our data looks like this.
df %>% head() continent year mean_lifeExp Africa 1952 39.13550 Africa 1957 41.26635 Africa 1962 43.31944 Africa 1967 45.33454 Africa 1972 47.45094 Africa 1977 49.58042
We will first write ggplot2 code to make the standard barplot. In this example we have used geom_col() to make barplot and colored the bars with continent variable. The last three lines of code here is gganimate specific. Within labs() we use “frame_time” to display time. And then we use one of the gganimate function or grammar classes, transition_time() to make a simple animation in R. Here the variable for transition_time() is year. And then we specify gganimate aesthetics ease_aes() to speicify the type of transition in animation.
p <- df %>% ggplot(aes(x=continent, y= mean_lifeExp, fill=continent)) + geom_col() + theme(legend.position = "none")+ labs(title = 'Year: {frame_time}', x= 'Continent',y = 'Mean Life Expectancy') + transition_time(year) + ease_aes('linear')
Voila we get a nice animation of life expectancy over time for each continent.