有什么办法可以在gganimate中使用transition_reveal在特定帧/时间点暂停?

时间:2018-10-31 21:30:07

标签: r gganimate

使用this来自Github上程序包Wiki的示例:

airq <- airquality
airq$Month <- format(ISOdate(2004,1:12,1),"%B")[airq$Month]

ggplot(airq, aes(Day, Temp, group = Month)) + 
  geom_line() + 
  geom_segment(aes(xend = 31, yend = Temp), linetype = 2, colour = 'grey') + 
  geom_point(size = 2) + 
  geom_text(aes(x = 31.1, label = Month), hjust = 0) + 
  transition_reveal(Month, Day) + 
  coord_cartesian(clip = 'off') + 
  labs(title = 'Temperature in New York', y = 'Temperature (°F)') + 
  theme_minimal() + 
  theme(plot.margin = margin(5.5, 40, 5.5, 5.5))

产生类似的东西:

enter image description here

我想知道是否有任何方法可以定义动画中特定点的暂停。例如在第10天,然后是20天,然后是动画完成时,然后再次循环。 geom_reveal没有可用的state_lengthtransition_length参数,因此我不确定是否可行。

编辑:程序包作者提到可以在twitter上使用,但我不知道他指的是什么“发布时机”。

2 个答案:

答案 0 :(得分:12)

从OP:

  

编辑:程序包作者提到可以在Twitter上进行操作,但我没有   知道他指的是什么“揭示时机”论点。

在Twitter上,Thomas Lin Pedersen指的是transition_reveal行如何驱动动画的帧。因此,我们可以为它提供一个变量,使其成为动画的“心跳”,同时保留绘图的原始变量。

我的第一种方法是创建一个新变量reveal_time,这将成为心跳。我会在暂停点增加更多的时间,以便动画在这些数据点上花费更多的时间。在这里,我通过在暂停点的日期添加10,而在其他日期仅添加1。

library(dplyr)
airq_slowdown <- airq %>%
  group_by(Month) %>%
  mutate(show_time = case_when(Day %in% c(10,20,31) ~ 10,
                                     TRUE           ~ 1),
         reveal_time = cumsum(show_time)) %>%
  ungroup()

然后我将其输入动画中,更改源数据框和transition_reveal行。

library(gganimate)
a <- ggplot(airq_slowdown, aes(Day, Temp, group = Month)) + 
  geom_line() + 
  geom_segment(aes(xend = 31, yend = Temp), linetype = 2, colour = 'grey') + 
  geom_point(size = 2) + 
  geom_text(aes(x = 31.1, label = Month), hjust = 0) + 
  transition_reveal(Month, reveal_time) +  ### Changed from OP
  coord_cartesian(clip = 'off') + 
  labs(title = 'Temperature in New York', y = 'Temperature (°F)') + 
  theme_minimal() + 
  theme(plot.margin = margin(5.5, 40, 5.5, 5.5))    
animate(a, nframe = 50)

enter image description here

但是当我这样做的时候,我意识到它并没有暂停-只是在减缓补间。有点“子弹时间”效果-很酷,但不完全是我想要的。

所以我的第二种方法是实际复制动画的暂停行。这样,就不会发生补间,而会有真正的停顿:

airq_pause <- airq %>%
  mutate(show_time = case_when(Day %in% c(10,20,31) ~ 10,
                               TRUE           ~ 1)) %>%
  # uncount is a tidyr function which copies each line 'n' times
  uncount(show_time) %>%
  group_by(Month) %>%
  mutate(reveal_time = row_number()) %>%
  ungroup()

enter image description here

答案 1 :(得分:2)

您可以使用 animate 函数的 end_pause 参数:

library(gganimate)
library(animation)

animation <- barplot +  transition_reveal(anho)
#barplot built in ggplot2

animate(animation, end_pause = 10, width=1000, height=600,fps = 5)