如何将gganimate生成的动画并排显示或在同一文档中展示?
如何并排显示gganimate生成的动画
我之前也踩过这个坑——gganimate生成的动画对象没法像静态ggplot图那样直接用patchwork拼接,不过有几个靠谱的办法能实现你想要的并排效果:
方法1:用magick包拼接动画帧
这个方法是先分别渲染两个动画的每一帧,再把对应帧横向拼接,最后合成一个完整的动画,适合需要导出成GIF/视频的场景:
首先加载所需包:
library(ggplot2) library(gganimate) library(magick)
定义你的两个动画对象(沿用你的代码):
anime_one <- 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') anime_two <- ggplot(mtcars, aes(factor(cyl), mpg, fill = factor(cyl))) + geom_boxplot() + transition_states( gear, transition_length = 2, state_length = 1 ) + enter_fade() + exit_shrink() + ease_aes('sine-in-out')
接下来渲染帧并拼接:
# 把两个动画渲染为magick帧列表 frames_one <- animate(anime_one, renderer = magick_renderer()) frames_two <- animate(anime_two, renderer = magick_renderer()) # 逐帧横向拼接两个动画的对应帧 combined_frames <- mapply( function(frame1, frame2) image_append(c(frame1, frame2), stack = FALSE), frames_one, frames_two, SIMPLIFY = FALSE ) # 合成最终的并排动画 combined_anime <- image_animate(image_join(combined_frames), fps = 10) # 预览动画 combined_anime # 保存为GIF(可选) image_write(combined_anime, "side_by_side_anime.gif")
方法2:在R Markdown中用HTML布局实现并排
如果你的目标是在编织后的HTML文档中显示并排动画,可以用HTML的flex布局来控制两个动画的位置,比你之前的方案更紧凑:
在你的R Markdown文档中加入这段代码:
<div style="display: flex; justify-content: space-around; margin: 20px 0;"> <div style="width: 45%;"> ```{r, echo=FALSE, fig.width=6, fig.height=4} animate(anime_one) ``` </div> <div style="width: 45%;"> ```{r, echo=FALSE, fig.width=6, fig.height=4} animate(anime_two) ``` </div> </div>
编织成HTML后,两个动画会并排显示在同一行,你可以调整width和样式参数来适配你的需求。
为什么你之前的尝试会失败?
- 方案一报错:因为
gganim_built(gganimate生成的动画对象)不是标准的ggplot对象,patchwork的ggplot_gtable方法没法处理它,所以直接用+拼接会抛出找不到方法的错误。 - 方案二只显示最后一个动画:当你用
anime_one + anime_two时,patchwork并没有真正拼接动画对象,只是返回了最后一个对象,所以animate()只会渲染它。
内容的提问来源于stack exchange,提问作者Steen Harsted
相关产品推荐
相关产品推荐

