transformr包动画无法在RStudio正常显示的问题求助
在RStudio中直接渲染transformr生成的动画而非仅保存本地GIF
我在RStudio 2023.12.0+369版本中使用transformr包,运行官方示例代码时,仅输出一系列静态图片而非GIF动画。示例代码如下:
library(transformr) library(tweenr) library(ggplot2) polyplot <- function(data) { p <- ggplot(data) + geom_polygon(aes(x, y, group = id, fill = col)) + scale_fill_identity() + coord_fixed(xlim = c(-1.5, 1.5), ylim = c(-1.5, 1.5)) plot(p) } star <- poly_star() star$col <- 'steelblue' circles <- poly_circles() circles$col <- c('forestgreen', 'firebrick', 'goldenrod')[circles$id] animation <- tween_polygon(star, circles, 'cubic-in-out', 40, id) %>% keep_state(10) ani <- lapply(split(animation, animation$.frame), polyplot)
尝试用saveGIF仅能将GIF保存到本地,无法在RStudio中直接渲染,重新加载显示效率极低。以下是两种直接在RStudio中预览动画的解决方案:
方法1:使用gganimate直接生成并渲染动画
gganimate与transformr深度兼容,可直接在RStudio Viewer面板生成并显示动画,同时支持导出:
library(transformr) library(tweenr) library(ggplot2) library(gganimate) # 准备动画数据 star <- poly_star() star$col <- 'steelblue' circles <- poly_circles() circles$col <- c('forestgreen', 'firebrick', 'goldenrod')[circles$id] animation <- tween_polygon(star, circles, 'cubic-in-out', 40, id) %>% keep_state(10) # 构建基础ggplot图形 base_plot <- ggplot(animation) + geom_polygon(aes(x, y, group = id, fill = col)) + scale_fill_identity() + coord_fixed(xlim = c(-1.5, 1.5), ylim = c(-1.5, 1.5)) # 添加动画逻辑并渲染 animated_plot <- base_plot + transition_states(.frame, transition_length = 4, state_length = 1) + ease_aes('cubic-in-out') # 在RStudio中直接预览动画 animate(animated_plot, fps = 20, width = 400, height = 400) # 可选:保存GIF到本地 anim_save("transformr_animation.gif", animated_plot)
transition_states会根据数据中的.frame列控制动画过渡,animate()函数直接在RStudio Viewer中输出动态效果,无需手动拆分帧。
方法2:使用magick将图片序列转为GIF并显示
如果需要保留原有的polyplot逻辑,可通过magick包将生成的静态图片组合为GIF并在RStudio中预览:
library(transformr) library(tweenr) library(ggplot2) library(magick) # 修改polyplot函数,返回ggplot对象而非直接绘制 polyplot <- function(data) { ggplot(data) + geom_polygon(aes(x, y, group = id, fill = col)) + scale_fill_identity() + coord_fixed(xlim = c(-1.5, 1.5), ylim = c(-1.5, 1.5)) } # 准备数据 star <- poly_star() star$col <- 'steelblue' circles <- poly_circles() circles$col <- c('forestgreen', 'firebrick', 'goldenrod')[circles$id] animation <- tween_polygon(star, circles, 'cubic-in-out', 40, id) %>% keep_state(10) # 生成所有帧的ggplot对象 plot_list <- lapply(split(animation, animation$.frame), polyplot) # 将ggplot对象转为magick图像 img_list <- lapply(plot_list, function(p) { img <- image_graph(width = 400, height = 400, res = 96) print(p) dev.off() img }) # 组合为GIF并在RStudio中显示 animated_gif <- image_join(img_list) %>% image_animate(fps = 20) print(animated_gif) # 可选:保存GIF image_write(animated_gif, "transformr_animation.gif")
image_graph将ggplot对象转换为magick可处理的图像格式,image_animate组合帧生成动画,print(animated_gif)会直接在RStudio Viewer中展示动态效果。
内容的提问来源于stack exchange,提问作者Emma
相关产品推荐
相关产品推荐

