10

我正在尝试使用gganimate涵盖 90 年的数据集创建一个 GIF,即我想要一个 GIF 运行 90 个州/年。但是,似乎gganimate只能处理不到 50 个州。

所以这里有一个例子:

library(tidyverse)
# devtools::install_github('thomasp85/gganimate')
library(gganimate)

df = expand.grid(  x = 1,
                   y = c(2,3),
                year = 1670:1760) %>% mutate( z = 0.03* year,
                                              u = .2 * year)

这一切都可以正常工作 49 年:

ggplot(data=df %>% filter(., year %in% 1670:1719) , aes()) + 
  geom_point( aes(x = x, y = y, fill = z, size = u), shape = 21 ) + 
  labs( title = 'Year: {closest_state}') +
  enter_appear() +
  transition_states(year, transition_length = 1, state_length = 2) 

示例1

然而,当我包括 50 年(或更多)年时,它变得很奇怪:

ggplot(data=df %>% filter(., year %in% 1670:1720) , aes()) + 
  geom_point( aes(x = x, y = y, fill = z, size = u), shape = 21 ) + 
  labs( title = 'Year: {closest_state}') +
  enter_appear() +
  transition_states(year, transition_length = 1, state_length = 2) 

示例2

如何为所有 90 年创建一个 GIF?欢迎任何想法!
我还是新手gganimate,我使用transition_states不正确吗?

4

1 回答 1

13

这与gganmiate动画使用固定数量的 100 帧有关。长达 50 年(请注意,1670:1719长度为 50,而不是 49),这没关系,但如果您想绘制更多年,则需要更多帧。您可以通过显式调用来控制帧数animate()

对于您的示例,这意味着您应该首先将绘图存储在变量中:

p <- ggplot(df) + 
      geom_point(aes(x = x, y = y, fill = z, size = u), shape = 21) + 
      labs( title = 'Year: {closest_state}') +
      enter_appear() +
      transition_states(year, transition_length = 1, state_length = 2)

然后,您可以通过键入以下任何内容来启动动画

p
animate(p)
animate(p, nframes = 100)

这三行是等价的。第一个是您在示例中所做的:这将隐式调用animate()以渲染动画。第二行进行animate()显式调用,第三行也显式将帧数设置为 100。由于nframes = 100是默认值,因此最后一行也与其他行相同。

为了使动画工作,您需要设置更高的帧数。100 帧工作了 50 年,因此 182 帧应该在您的完整数据帧中工作 91 年。同样,以下两行是相同的:

animate(p, nframes = 182)
animate(p, nframes = 2 * length(unique(df$year)))

现在它起作用了:

在此处输入图像描述

我不确定为什么您需要的帧数是多年的两倍,但是在阅读了文档中的以下声明之后transition_states()

然后它在定义的状态之间进行补间并在每个状态处暂停。

我猜想一帧用于两年之间的过渡,一帧用于表示给定年份的日期。

这意味着您实际上需要的帧数少于年数的两倍,因为在去年之后的过渡不需要帧。实际上,gganimate()fornframes = 100和的输出nframes = 182分别为:

Frame 99 (100%)
Finalizing encoding... done!

Frame 181 (100%)
Finalizing encoding... done!

因此,如果我的猜测是正确的,它确实创建了预期的帧数。

于 2018-09-16T08:50:47.740 回答