在gganimate中使用transition_reveal累计绘制线条

时间:2019-10-17 15:06:22

标签: r gganimate

有没有一种方法可以在gganimate中使用transition_reveal()来一条一条地画线-或使用其他过渡功能的解决方法。

library(tidyverse)
library(gganimate)
set.seed(1)
d <- tibble(x = 1:100, a = cumsum(rnorm(100)), b = cumsum(rnorm(100))) %>%
  pivot_longer(cols = a:b, names_to = "grp", values_to = "y")
d
# # A tibble: 200 x 3
#        x grp        y
#    <int> <chr>  <dbl>
#  1     1 a     -0.626
#  2     1 b     -0.620
#  3     2 a     -0.443
#  4     2 b     -0.578
#  5     3 a     -1.28 
#  6     3 b     -1.49 
#  7     4 a      0.317
#  8     4 b     -1.33 
#  9     5 a      0.646
# 10     5 b     -1.99 
# # ... with 190 more rows

我希望一次只显示一条线-以便第二条线的绘图在第一条线完成后开始(一个框架101)-而不是同时绘制两条线... < / p>

ggplot(data = d, mapping = aes(x = x, y = y, colour = grp)) +
  geom_line() +
  transition_reveal(along = x) 

enter image description here

1 个答案:

答案 0 :(得分:4)

我们可以创建一个辅助列,将b的所有点放在a的所有点之后:

d %>%
  arrange(grp, x) %>%
  mutate(x_reveal = row_number()) %>%
  ggplot(aes(x = x, y = y, colour = grp)) +
    geom_line() +
    transition_reveal(along = x_reveal) 

enter image description here