18

利用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))

产生类似的东西:

在此处输入图像描述

我想知道是否有任何方法可以在特定点定义动画中的暂停。例如,在第 10 天,然后是第 20 天,然后在动画结束时,再次循环之前。geom_reveal没有可用state_lengthtransition_length参数,所以我不确定这是否可能。

编辑:包作者在特上提到它是可能的,但我不知道他指的是什么“揭示时间”论点。

4

2 回答 2

27

来自 OP:

编辑:包作者提到有可能[这样做],但我不知道他指的是什么“揭示时间”论点。

在 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(reveal_time) +  # Edit, previously had (Month, reveal_time)
  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)

在此处输入图像描述

但是当我这样做时,我意识到它并没有暂停——它只是减慢了补间。有点像“子弹时间”的效果——很酷,但不是我想要的。

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

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()

在此处输入图像描述

于 2018-10-31T23:44:33.643 回答
2

您可以使用end_pauseanimate 函数的参数:

library(gganimate)
library(animation)

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

animate(animation, end_pause = 10, width=1000, height=600,fps = 5)
于 2021-01-15T23:55:12.120 回答