为ggplot2图添加图层的过程设置动画

eme*_*hex 3 r ggplot2 gganimate

我开始熟悉了gganimate,但我希望进一步扩展我的GIF.

例如,我可以抛出frame一个变量,gganimate但如果我想动画添加全新图层/ geoms /变量的过程怎么办?

这是一个标准的gganimate例子:

library(tidyverse)
library(gganimate)

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

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

但是如果我想要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")
Run Code Online (Sandbox Code Playgroud)

这怎么可能实现?

Mar*_*son 5

您可以手动frame为每个图层添加美感,但它会立即包含所有框架的图例(我故意相信,保持比率/边距等正确:

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

在此输入图像描述

如果你想自己添加东西,甚至看看传说,标题等是如何移动的,你可能需要回到较低级别的包,并自己构建图像.在这里,我使用的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"
 )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述