动画化向 ggplot2 图添加图层的过程

Animate the process of adding layers to a ggplot2 plot

我开始熟悉 gganimate,但我想进一步扩展我的 gif。

例如,我可以在 gganimate 中的一个变量上抛出一个 frame,但是如果我想动画化添加全新 layers/geoms/variables 的过程怎么办?

这是一个标准的 gganimate 示例:

library(tidyverse)
library(gganimate)

p <- ggplot(mtcars, aes(x = hp, y = mpg, frame = cyl)) +
    geom_point()

gg_animate(p)

但是如果我想让 gif 动起来怎么办:

# frame 1
ggplot(mtcars, aes(x = hp, y = mpg)) +
    geom_point()

# frame 2
ggplot(mtcars, aes(x = hp, y = mpg)) +
    geom_point(aes(color = factor(cyl)))

# frame 3
ggplot(mtcars, aes(x = hp, y = mpg)) +
    geom_point(aes(color = factor(cyl), size = wt))

# frame 4
ggplot(mtcars, aes(x = hp, y = mpg)) +
    geom_point(aes(color = factor(cyl), size = wt)) +
    labs(title = "MTCARS")

如何实现?

您可以手动向每一层添加 frame 美学,尽管它会立即包含所有帧的图例(我相信是有意保持 ratios/margins 等正确:

saveAnimate <-
  ggplot(mtcars, aes(x = hp, y = mpg)) +
  # frame 1
  geom_point(aes(frame = 1)) +
  # frame 2
  geom_point(aes(color = factor(cyl)
                 , frame = 2)
             ) +
  # frame 3
  geom_point(aes(color = factor(cyl), size = wt
                 , frame = 3)) +
  # frame 4
  geom_point(aes(color = factor(cyl), size = wt
                 , frame = 4)) +
  # I don't think I can add this one
  labs(title = "MTCARS")

gg_animate(saveAnimate)

如果您希望能够自己添加内容,甚至查看图例、标题等如何移动内容,您可能需要退回到 lower-level 包,并自己构建图像.在这里,我使用的是 animation 包,它允许您循环浏览一系列情节,没有任何限制(它们根本不需要相关,所以当然可以显示移动情节区域的东西。请注意,我相信这需要在您的计算机上安装 ImageMagick。

p <- ggplot(mtcars, aes(x = hp, y = mpg))

toSave <- list(
  p + geom_point()
  , p + geom_point(aes(color = factor(cyl)))
  , p + geom_point(aes(color = factor(cyl), size = wt))
  , p + geom_point(aes(color = factor(cyl), size = wt)) +
    labs(title = "MTCARS")
)

library(animation)

saveGIF(
  {lapply(toSave, print)}
  , "animationTest.gif"
 )

animation 包不会强制您在数据中指定帧。请参阅本页底部的示例 here,其中动画包装在一个大 saveGIF() 函数中。您可以指定单个帧和所有内容的持续时间。

这样做的缺点是,与漂亮的 gganimate 函数不同,基本的逐帧动画不会保持情节 dimensions/legend 不变。但是,如果您可以通过破解的方式为每一帧准确显示您想要的内容,那么基本的动画包将为您提供很好的服务。

较早答案中的 gganimate 命令自 2021 年起已弃用,不会完成 OP 的任务。

基于 Mark 的代码,您现在可以简单地创建一个具有多层几何图形的静态 ggplot 对象,然后添加 gganimate::transition_layers 函数来创建在静态绘图中从一层过渡到另一层的动画。 enter_fade()enter_grow() 等补间函数控制元素如何进出帧。

library(tidyverse)
library(gganimate)

anim <- ggplot(mtcars, aes(x = hp, y = mpg)) +
  # Title
  labs(title = "MTCARS") +
  # Frame 1
  geom_point() +
  # Frame 2  
  geom_point(aes(color = factor(cyl))) +
  # Frame 3
  geom_point(aes(color = factor(cyl), size = wt)) +
  # gganimate functions
  transition_layers() + enter_fade() + enter_grow()

# Render animation
animate(anim)