Search code examples
rggplot2gganimate

Using GGanimate make points of group in a grouped scatter plot disappear once all of them appeared


I am trying to make an grouped scatter plot in which points appear at different time points (based on a time variable) and once all points of a certain group have appeared all of them disappear. The different groups do not start at the same time point and do not end at the same end point and also do not have the same amount of data points.

I guess this should be some combination of transition_time() (in the real data an actual time stamp is used), exit_disappear() and/or shadow_mark(), but I cannot seem to get this to work.

I have tried this, but it does not yield the results I need. I need for example group A to all appear one by one and then disappear after time point 15. and need all of group B to start appearing after time point 21, one by one and then disappear after time point 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()

Solution

  • I think shadow_wake instead of shadow_mark may yield the result you are looking for:

    # 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

    Data:

    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)