如何保存使用 gganimate 包创建的 gif 帧

And*_*ade 6 r gganimate

我将使用 gapminder 数据作为示例。假设我创建了这个动画:

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")
Run Code Online (Sandbox Code Playgroud)

现在,我想访问构成 gif 的单个图像(帧)。有没有办法在 gganimate 中做到这一点,还是我需要使用动画包?

Sti*_*ibu 15

gganimate自从提出这个问题以来,已经发生了很大变化。在当前版本 (0.9.9.9999) 中,有一种方法可以将每个帧存储为自己的文件。

首先,我需要创建动画,它与新版本的包看起来有点不同:

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

然后可以使用显示动画

animate(p)
Run Code Online (Sandbox Code Playgroud)

渲染由所谓的渲染器负责。要将动画存储在单个动画 gif 中,您可以使用

animate(p, nframes = 24, renderer = gifski_renderer("gganim.gif"))
Run Code Online (Sandbox Code Playgroud)

请注意,我已手动设置要创建的帧数。默认情况下,使用 100 帧,我在这里选择了一个较小的数字。选择正确数量的帧有时可能有点棘手,如果您得到奇怪的结果,请尝试使用更多帧。

或者,您可以使用 afile_renderer()将每个帧写入其自己的文件

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

这将命名文件写gganim_plot0001.pnggganim_plot0002.png等来的目录~/gganim。修改值prefixdevice如果你想不同的文件名或不同的文件类型。(我将它们设置为默认值。)