【问题标题】:Using gganimate to export gif使用 gganimate 导出 gif
【发布时间】:2018-12-28 15:28:57
【问题描述】:

gganimate 包创建 gif(来自here 的 MWE 代码):

    library(ggplot2)
    #devtools::install_github('thomasp85/gganimate')
    library(gganimate)

    p <- ggplot(mtcars, aes(factor(cyl), mpg)) + 
            geom_boxplot() + 
            # Here comes the gganimate code
            transition_states(
                    gear,
                    transition_length = 2,
                    state_length = 1
            ) +
            enter_fade() + 
            exit_shrink() +
            ease_aes('sine-in-out')

现在如何导出这个 gif?在gganimate 的先前(现已存档)版本中,这很简单:

    gganimate(p, "output.gif")

但是,我在当前的 gganimate 包中找不到等效功能。


注意:这个问题似乎与我从中获取 MWE 代码的问题完全相同。但是,gganimate 已更新,在新版本中,在查看器窗格中显示动画与导出动画似乎是不同的问题。

【问题讨论】:

  • 您是否尝试过使用image_write()
  • 有一个animate函数。
  • @Miha。以前不是,但是当我尝试时,我注意到p 不是魔法图像对象,我不确定如何将其转换为一个。 @Axeman,我做到了,但不知道如何按照file="p.gif"
  • @Miha,我愿意,因此包中的错误:Error: The 'image' argument is not a magick image object.。也许我做错了什么?你将如何使用magick 将 p 导出为 gif?
  • image_graphdev.off() 应该可以工作。或者另一种选择:使用image_animateimage_write。所以试试save.gif &lt;- image_animate(p, fps = 2); image_write(save.gif, "output.gif")

标签: r ggplot2 gganimate


【解决方案1】:

gganimate 1.0.6 和 gifski 0.8.6

根据 @Ronak Shah 的建议,我使用 gganimate 包中的 anim_save() 添加了更新的答案 - 因为它使用 gifski now 呈现 .gif 输出。

library(ggplot2)
library(gganimate)
# install.package("gifski") #if not already installed

p <- ggplot(mtcars, aes(factor(cyl), mpg)) + 
  geom_boxplot() + 
  transition_states(
    gear,
    transition_length = 2,
    state_length = 1
  ) +
  enter_fade() + 
  exit_shrink() +
  ease_aes('sine-in-out')

anim_save("filenamehere.gif", p)

【讨论】:

    【解决方案2】:

    你可以这样做:

    anim <- animate(p)
    magick::image_write(anim, path="myanimation.gif")
    

    【讨论】:

    • 在 GitHub 中,提到 gganimate 不使用 ImageMagick 参见 here。适当的方法是使用anim_save(),例如anim_save("filenamehere.gif", anim)
    • 使用这个方法报错:错误:动画对象没有指定save_animation方法。
    • @VojtěchKania 我的回答中的方法还是 EJJ 评论中的方法?
    • 您的方法报告:错误:“图像”参数不是魔术图像对象。
    • @VojtěchKania 好的。有些事情发生了变化。无论如何,EJJ的方法看起来更好。这应该是答案。
    猜你喜欢
    • 2020-03-18
    • 2018-08-15
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多