【问题标题】:How to save frames of gif created using gganimate package如何保存使用 gganimate 包创建的 gif 帧
【发布时间】:2018-08-15 17:45:02
【问题描述】:

我将使用 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 中做到这一点,还是我需要使用动画包?

【问题讨论】:

  • 可能有帮助:来自小插图 (github.com/dgrtwo/gganimate):“当在 knitr 中运行时(并结合 knitr 的 fig.show = "animate" 块选项),它会按顺序显示每个图形让 knitr 创建动画。”

标签: r gganimate


【解决方案1】:

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 帧,我在这里选择了一个较小的数字。有时选择正确的帧数可能有点棘手,如果得到奇怪的结果,请尝试使用更多帧。

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

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

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

【讨论】:

    【解决方案2】:

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

    为了更流畅的动画

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

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

    myanimation + 
      enter_grow() +
      exit_fade()
    

    加速/减速

    • 如果您选择了较高的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

    【讨论】:

      猜你喜欢
      • 2018-12-28
      • 2020-03-18
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 2018-08-10
      • 2016-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多