我开始熟悉gganimate,但我想进一步扩展gifs。
例如,我可以在frame中的一个变量上抛出一个gganimate,但是如果我想动画化添加全新层/geoms/变量的过程呢?
下面是一个标准的gganimate示例:
library(tidyverse)
library(gganimate)
p <- ggplot(mtcars, aes(x = hp, y = mpg, frame = cyl)) +
geom_point()
gg_animate(p)但如果我想让礼物有生气呢:
# 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")如何才能做到这一点?
发布于 2016-10-06 16:24:05
您可以手动为每一层添加一个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)

如果你想自己添加一些东西,甚至能看到传说,标题等如何移动东西,你可能需要退一步到一个较低级别的包,并自己构造图像。在这里,我使用的是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"
)

发布于 2021-01-26 20:26:39
前面的答案中的gganimate命令在2021年被废弃,无法完成OP的任务。
在Mark代码的基础上,您现在可以简单地创建一个具有多个分层geoms的静态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)发布于 2016-10-07 07:01:06
animation包不会强迫您在数据中指定框架。参见本页这里底部的示例,其中动画被包装在一个大的saveGIF()函数中。您可以指定单个帧和所有内容的持续时间。
这样做的缺点是,与漂亮的gganimate函数不同,基本的逐帧动画无法保持情节维度/图例常量。但是,如果你能破解你的方式来显示你想要的每一帧,基本的动画包将很好地为你服务。
https://stackoverflow.com/questions/39900656
复制相似问题