Animate ggplot time series plot with a sliding window

天大地大妈咪最大 提交于 2019-12-05 10:42:10

I wasn't sure how to do this entirely within the view_* framework of gganimate, but here's an approach using a bit of manual preparation. I copy the data frame for every frame I want to show, and then filter to the data points I want each frame to see. gganimate::view_follow sets each frame's view range to only show the data for that frame.

library(tidyverse)
library(gganimate)
df <- as.data.frame(cumsum(rnorm(1:10000))) %>% rename(y = 1)
df <- mutate(df, seq = seq(1, 10000, by = 1))

window_width = nrow(df)/5  # How much of the whole data to show at once
frames = 200   # Increase to make smoother animation & bigger file
shift_per_frame = (nrow(df) - window_width) / frames

# This bit of purrr copies the whole data frame [frames] times, identifying each with "id"
df_copied <- map_df(seq_len(frames), ~df, .id = "id") %>%
  mutate(id = as.integer(id)) %>%
  filter(seq >= id * shift_per_frame,
         seq <= id * shift_per_frame + window_width)

a <- ggplot(df_copied, aes(x = seq, y = y)) + 
  geom_line() +
  transition_manual(id) +
  view_follow()

animate(a, nframes = frames)

...or with view_follow(fixed_y = TRUE):

(Note, for 10k values, it will look better to subdivide into more frames for smoother movement, but this will make a larger file than I could attach here.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!