使用滑动窗口为ggplot时间序列图添加动画效果

7
我正在寻找一种方法来对长时间序列图进行动画处理,而不会失去分辨率。我希望视图可以在数据上“平移”,从开始到结束显示一个滑动的子集。
假设我有以下内容:
  library(ggplot2)
  library(dplyr)
  library(gganimate)

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

  ggplot(df, aes(x = seq, y = y)) + 
    geom_line()

enter image description here

我想创建一种动画,通过仅聚焦于一段数据并沿着时间轴滑动来展示更多细节。可以想象,在放大镜下查看这个系列,并在其下方滑动图表... 这就是我试图实现的效果。通过 gganimate 可以实现吗?如果不行,有什么建议吗?
1个回答

19

我不确定如何完全在gganimate的view_*框架内完成此操作,但这里有一种使用少量手动准备的方法。我为要显示的每个帧复制数据框,然后筛选出每个帧要查看的数据点。gganimate::view_follow将每个帧的视图范围设置为仅显示该帧的数据。

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)

在此输入图片描述

...或使用view_follow(fixed_y = TRUE)在此输入图片描述

(请注意,对于10k的值,将其细分为更多框架会使移动更加平滑,但这将生成一个比我可以附加的文件要大的文件。)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接