How to create an animated chart (gif) in R for beginners

Mariana Maroto
3 min readMar 5, 2021

--

How many times a week do you see a news article or presentation at work with a time-series chart like this one?

New York Times: Link

Probably a lot! Line charts are great at presenting information across time. They clearly show growth, stagnation, or decline. However, if you want to make your line chart stand-out from the rest, keep reading to learn how to animate your line chart and share it as a gif. Yes, a gif. Like the funny memes you send to your friends via IM.

1.Choose your dataset: For this example, we will be using Gapminder.org’s dataset on cell phones by country. Gapminder is an educational non-profit that fights common misconceptions about our world. Actually, if you haven’t heard about Gapminder, I would recommend forgetting about making this chart and exploring their website instead (jk). In this dataset, we have the amount of cell phones per 100 people within each country where each column corresponds to a specific year.

# read dataset
data <- read.csv('cell_phones_per_100_people.csv', stringsAsFactors = FALSE)
Original Dataset

2. Clean data: Like in any data visualization project (and by any I really mean all) we have to clean and rearrange the data a bit. In this case we want to melt the dataset. Instead of each row corresponding to a specific country, each row should correspond to a specific country + year combination.

library(reshape2)
library(dplyr)
# rearrange dataset
data <- melt(data, id=c("country"))
data$year <- gsub("X","", data$variable)
data$variable <- NULL
data$year <- as.Date(data$year, format = "%Y")
# select countries you would like to show
plot_data <- data %>%
filter(country %in% c("United States", "Costa Rica", "France", 'China'))
Cleaned Data

3. Create animated plot: Use gganimate to easily create your animated plot. You can select your title and y-axis label by editing code below.

library(gganimate)
library(hrbrthemes)
# Plot
plot_data %>%
ggplot( aes(x=year, y=value, group=country, color=country)) +
geom_line() +
geom_point() +
ggtitle("Phone Adoption") +
theme_ipsum() +
ylab("Cell Phones per 100 People") +
transition_reveal(year)

4. Save as gif: And voilà! Save your plot as a gif to your desktop and send it to your friends or coworkers to impress them!

In this case, wow! we see Costa Ricans cell phone adoption sky-rocket around 2010 and surpassing the US! I think I got my first cell phone around that time … so that explains it.

After-thoughts: Why are there so many more phones than people? Maybe I will investigate this in another post …

# Save as gif:
anim_save("Phone Adoption.gif")

--

--

Mariana Maroto
Mariana Maroto

Written by Mariana Maroto

Research Consultant for Tech and Telco | M.S. in Data Science

No responses yet