一旦它们全部出现,使用GGanimate可使分组散点图中的组点消失

时间:2019-02-26 09:10:28

标签: r ggplot2 gganimate

我正在尝试制作一个散点图,其中点出现在不同的时间点(基于时间变量),并且一旦某个组的所有点都出现了,所有这些点都消失了。不同的组不会在同一时间点开始,也不会在同一终点处结束,也没有相同数量的数据点。

我想这应该是transition_time()(在实际数据中使用实际时间戳),exit_disappear()和/或shadow_mark()的某种组合,但我似乎无法理解这一点去工作。

我已经尝试过了,但是没有得到我需要的结果。例如,我需要A组全部一次出现,然后在时间点15之后消失。并且需要B组全部开始在时间点21之后出现,一个接一个,然后在时间点45之后消失。

library(ggplot2)
library(gganimate)
library(tibble)

# data
x <- c(-15:-1, -5:19,  1:45, -10:4)
y <- x + rnorm(100, 0, 2) + c(rep(-10, 15), rep(20, 25), rep(-5, 45), rep(8, 15))
id <- c(rep("A", 15), rep("B", 25), rep("C", 45), rep("D", 15))
time <- c(1:15, 21:45, 1:45, 41:55)
tib <- tibble(x,y, id, time)

# does not disappear after one id is done
anim_tib1 <- ggplot(tib, aes(x = x, y = y, col = id, group = id))+
  geom_point(size = 2)+ 
  transition_time(time = time)+
  exit_disappear()+
  shadow_mark()

# this works, but now there is no trail 
anim_tib2 <- ggplot(tib, aes(x = x, y = y, col = id, group = id))+
  geom_point(size = 2)+ 
  transition_components(time)+
  exit_disappear()

# this almost yields the same result as the first try
anim_tib3 <- ggplot(tib, aes(x = x, y = y, col = id, group = id))+
  geom_point(size = 2)+ 
  transition_components(time)+
  exit_disappear()+
  shadow_mark()

1 个答案:

答案 0 :(得分:1)

我认为shadow_wake而非shadow_mark可能会产生您想要的结果:

# modified code from anim_tib1
ggplot(tib, aes(x = x, y = y, col = id, group = id)) +
  geom_point(size = 2) + 
  transition_time(time = time) +
  exit_disappear() +
  shadow_wake(wake_length = 1, size = NULL, alpha = NULL, wrap = FALSE)

plot

数据:

set.seed(123)
x <- c(-15:-1, -5:19,  1:45, -10:4)
y <- x + rnorm(100, 0, 2) + c(rep(-10, 15), rep(20, 25), rep(-5, 45), rep(8, 15))
id <- c(rep("A", 15), rep("B", 25), rep("C", 45), rep("D", 15))
time <- c(1:15, 21:45, 1:45, 41:55)
tib <- tibble(x, y, id, time)
rm(x, y, id, time)