Search code examples
rggplot2ggplotlygganimate

gganimate for random walk model


I have created a random walk plot using ggplot2 (code below). I wondered if it would be possible to use the gganimate package so that the random walk process (the black line in the plot) gradually appears but stops once it touches the grey horizontal dashed line.

set.seed(3344)

create_random_walk <- function(number=500){
  data.frame(x = rnorm(number),
             rown = c(1:500)) %>%
    mutate(xt = cumsum(x))
}

randomwalkdata <- rbind(mutate(create_random_walk(), run = 1))

p <- ggplot(randomwalkdata, aes(x = rown, y = xt)) + 
  geom_line() +
  labs(x = '\nTime (arbitrary value)', y = 'Evidence accumulation\n') +
  theme_classic()

p + geom_segment(aes(x = 0.5, xend = 500, y = 25, yend = 25, linetype = 2), colour = "grey", size = 1, show.legend = FALSE) +
  scale_linetype_identity()

enter image description here

Can anybody help?


Solution

  • library(gganimate); library(dplyr)
    animate(
      ggplot(randomwalkdata |> filter(cumsum(lag(xt, default = 0) >= 25) == 0), 
           aes(x = rown, y = xt)) + 
      geom_line() +
      geom_point(data = . %>% filter(rown == max(rown)), 
             size = 10, shape = 21, color = "red", stroke = 2) +
      labs(x = '\nTime (arbitrary value)', y = 'Evidence accumulation\n') +
      theme_classic() +
      annotate("segment", x = 0.5, xend = 500, y = 25, yend = 25, linetype = 2, 
                   colour = "grey", linewidth = 1) +
      scale_linetype_identity() +
      transition_reveal(rown), 
      end_pause = 20, width = 600)
    

    enter image description here