问题
I will use the gapminder data as an example. Let's say I create this animation:
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")
Now, I want to have access to the individual images (frames) that constitute the gif. Is there a way to do this in gganimate or do I need to use the animation package?
回答1:
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.)
来源:https://stackoverflow.com/questions/49155038/how-to-save-frames-of-gif-created-using-gganimate-package