使用 ggplot 和 gganimate 制作动画

Animating with ggplot and gganimate

我正在尝试学习 gganimate 的动画情节,我想知道是否有人对我 运行 遇到的问题有提示。为了使事情变得简单,我通过在 RStudio Cloud 中创建一个新项目,安装 ggplot2gganimatedatasauRus 包,并遵循来自 Isaac Faber:

library(datasauRus)
library(ggplot2)
library(gganimate)
ggplot(datasaurus_dozen, aes(x=x,y=y)) +
  geom_point() + 
  theme_minimal() + 
  transition_states(dataset,3,1) +
  ease_aes()

这会创建一系列 .PNG 文件,但我看不到动画。有些人似乎建议我可以使用 "print" 函数查看它,但这也不起作用。

我也无法将其导出为 .GIF,尽管我遵循了 给出的建议。具体来说,magick 包对我不起作用(我得到关于我的图像不是 magick 图像对象的相同错误),当我尝试以下代码时:

p <- ggplot(datasaurus_dozen, aes(x=x,y=y)) +
  geom_point() + 
  theme_minimal() + 
  transition_states(dataset,3,1) +
  ease_aes()
anim <- animate(p)
anim_save("myfilename.gif",anim)

R 告诉我

animation object does not specify a save_animation method.

我一直找不到告诉我如何指定 save_animation 方法的示例或文档。如果有人对此主题有建议,将不胜感激!

你走多了一步:

library(datasauRus) 
library(ggplot2) 
library(gganimate)

p <- ggplot(datasaurus_dozen, aes(x=x,y=y)) +
geom_point() +
theme_minimal() +
transition_states(dataset,3,1) + 
ease_aes() 

anim_save("myfilename.gif",p)

我通过在 animate() 中指定 gifski_renderer() 解决了这个问题:

library(tidyverse)
library(gganimate)
library(gapminder)

g <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
  geom_point(alpha = 0.7, show.legend = FALSE) +
  scale_colour_manual(values = country_colors) +
  scale_size(range = c(2, 12)) +
  scale_x_log10() +
  facet_wrap(~continent) +
  # Here comes the gganimate specific bits
  labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') +
  transition_time(year) +
  ease_aes('linear')

animate(g, height=400, width=600, renderer=gifski_renderer())

anim_save("gapminder.gif", g)

注意:这是 animate() 的默认渲染器,但不知何故需要明确指定。第一次完成后,我不再需要设置它,这是一种我无法解释的行为。