How to save frames of gif created using gganimate package

gganimate has changed a lot since this question was asked. In the current version (0.9.9.9999), there is a way to store each frame as its own file.

First, I need to create the animation, which looks a bit different with the new version of the package:

p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent)) +
      geom_point() +
      scale_x_log10() +
      transition_states(year, 1, 5)

The animation can then be shown using

animate(p)

The rendering is taken care of by so called renderers. To store the animation in a single animated gif, you can use

animate(p, nframes = 24, renderer = gifski_renderer("gganim.gif"))

Note that I have manually set the number of frames to be created. By default, 100 frames are used and I chose a smaller number here. Picking the right number of frames can be a bit tricky at times and if you get weird results, try using more frames.

Alternatively, you can use a file_renderer() to write each frame to its own file

animate(p, nframes = 24, device = "png",
        renderer = file_renderer("~/gganim", prefix = "gganim_plot", overwrite = TRUE))

This will write files named gganim_plot0001.png, gganim_plot0002.png, etc. to the directory ~/gganim. Modify the values for prefix and device if you want different file names or different file types. (I set them to the defaults.)

Tags:

R

Gganimate