使用滑动窗口对ggplot时间序列图进行动画处理 [英] Animate ggplot time series plot with a sliding window

查看:159
本文介绍了使用滑动窗口对ggplot时间序列图进行动画处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在不损失分辨率的情况下为长时间序列图制作动画的方法.我希望该视图在数据之间平移",以显示从头到尾的滑动子集.

I'm looking for ways to animate a long time series plot without losing resolution. I would like the view to "pan" across the data, showing a sliding subset of it from the beginning to the end.

假设我有以下内容:

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

我想创建一个动画,以显示更多细节,方法是一次只关注数据的一部分,然后从头到尾滑动.想象一下通过放大镜放大该系列,同时在下方滑动图...这就是我要达到的效果.是否可以通过gganimate?如果没有,有什么建议吗?

I'd like to create an animation that shows more detail by just focusing on one section of the data at a time, and sliding along from the beginning to the end. Imagine looking at the series through a magnifying lens while sliding the plot underneath... that's the effect I'm trying to achieve. Is it possible through gganimate? If not, any suggestions?

推荐答案

我不确定如何完全在gganimate的view_*框架内完成此操作,但这是一种使用一些手动准备工作的方法.我复制要显示的每个帧的数据帧,然后过滤到希望每个帧看到的数据点. gganimate::view_follow将每个框架的视图范围设置为仅显示该框架的数据.

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)

...或view_follow(fixed_y = TRUE):

(请注意,对于10k值,最好将其细分为更多的帧以使移动更平滑,但这会产生比我在此处附加的文件大的文件.)

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

这篇关于使用滑动窗口对ggplot时间序列图进行动画处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆