【问题标题】:gganimate for random walk model用于随机游走模型的 gganimate
【发布时间】:2023-02-14 03:48:32
【问题描述】:

我使用 ggplot2(下面的代码)创建了一个随机游走图。我想知道是否可以使用 gganimate 包,使随机游走过程(图中的黑线)逐渐出现,但一旦触及灰色水平虚线就停止。

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()

有人可以帮忙吗?

【问题讨论】:

  • “一旦它触及灰色水平线就停止”,你的意思是动画应该在 Time ~200 结束,或者它应该在继续之前暂停在那里?

标签: r ggplot2 ggplotly gganimate


【解决方案1】:
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 = '
Time (arbitrary value)', y = 'Evidence accumulation
') +
  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)

【讨论】:

  • 谢谢乔恩 - 这太棒了!有什么方法可以添加当黑线接触灰线时出现的圆圈(没有填充但有红色轮廓)?
  • 当然,你可以添加一个只有最后一个点的图层,然后把它做成一个圆圈。见编辑。
猜你喜欢
  • 2014-03-26
  • 1970-01-01
  • 2021-05-05
  • 1970-01-01
  • 1970-01-01
  • 2014-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多