6

我将以 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")

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

4

2 回答 2

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)

然后可以使用显示动画

animate(p)

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

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

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

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

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

这会将名为gganim_plot0001.png,gganim_plot0002.png等的文件写入目录~/gganim。如果需要不同的文件名或不同的文件类型prefix,请修改值。device(我将它们设置为默认值。)

于 2018-09-16T19:05:55.950 回答
2

@Stibu 的回答非常好。以下是一些额外的提示:

为了更流畅的动画

  • 设置nframes为动画中单个绘图数量的倍数。例如,如果您在动画中有 52 个情节(一年中的每周一个情节),请尝试设置nframes = (4 * 52)nframes = (6 * 52)

  • 尝试添加enter_grow()exit_fade()如果您还没有添加(它们可以添加到许多没有参数的动画中)

myanimation + 
  enter_grow() +
  exit_fade()

加速/减速

  • 如果您选择了 high nframe,您的动画可能会很慢。您可以通过设置适当的来更改动画的速度duration,例如
animate(myanimation, 
  nframes = 312, 
  renderer = gifski_renderer("new_users_weekly.gif"), 
  duration = 14) # Duration in seconds

在 RMarkdown(或其他网页)中使用保存的 gif

插入.gif结果来自

animate(myanimation, renderer = gifski_renderer("new_users_weekly.gif")

进入网页或 RMarkdown 可以简单地完成:

<img src="new_users_weekly.gif" alt="animation"/>

更多信息

https://cran.r-project.org/web/packages/gganimate/gganimate.pdf#page=4

于 2020-05-01T13:31:27.360 回答