代码之家  ›  专栏  ›  技术社区  ›  Nautica

有没有办法在特定的帧/时间点暂停并在gganimate中显示过渡?

  •  10
  • Nautica  · 技术社区  · 7 年前

    利用 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_length 或 transition_length 参数可用,所以我不确定这是否可行。

    编辑 :软件包作者提到在 twitter

    1 回复  |  直到 7 年前
        1
  •  25
  •   Jon Spring    6 年前

    从OP:

    知道他指的是什么“揭示时机”。

    在Twitter上, Thomas Lin Pedersen was referring 如何 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()
    

    然后我将其输入到动画中,更改源数据帧和 过渡层 线路。

    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)
    

    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

        2
  •  2
  •   r0berts    5 年前

    你可以用 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)