Using gg_animate to create a gif

B. Washington picture B. Washington · Feb 15, 2016 · Viewed 7k times · Source

Is there a way to implement gg_animate in R to produce a gif. I already have my ggmaps created and saved as PDFs. I would like to create an animation which scrolls through those maps maybe holding on each image for 1 or 2 seconds. Is there a way to do this in R or should I use some sort of gif creator - if so any suggestions?

Thanks much

Answer

Jonathan Carroll picture Jonathan Carroll · Feb 15, 2016

Update Jul2018: gganimate() has undergone a rewrite and is now much improved. The previous API is only available through the archived version and should not be expected to work with the new version.

With the new version:

library(gapminder)
library(gganimate)

## standard ggplot2
ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
  geom_point(alpha = 0.7, show.legend = FALSE) +
  scale_colour_manual(values = country_colors) +
  scale_size(range = c(2, 12)) +
  scale_x_log10() +
  # Here comes the gganimate specific bits
  labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') +
  transition_time(year) +
  ease_aes('linear')

Producing the much smoother graphic

enter image description here

Original Answer:

I found the gganimate package to do quite well at this.

library(gapminder)
library(ggplot2)
theme_set(theme_bw())
p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent, frame = year)) +
  geom_point() +
  scale_x_log10()

library(gganimate)

gganimate(p)

gganimate(p, "output.gif")

enter image description here

Update Dec2016: gganimate() now replaces gg_animate() and adds cowplot as a dependency (should auto-install once Issue #32 is resolved).