R - 使用 ggplot2 在线图中绘制不同时间序列的滚动平均值

R - Plot the rolling mean of different time series in a lineplot with ggplot2

我想用 ggplot2 绘制不同时间序列数据的滚动平均值。我的数据具有以下结构:

library(dplyr)
library(ggplot2)
library(zoo)
library(tidyr)

df <- data.frame(episode=seq(1:1000), 
                 t_0 = runif(1000), 
                 t_1 = 1 + runif(1000), 
                 t_2 = 2 + runif(1000))
df.tidy <- gather(df, "time", "value", -episode) %>% 
  separate("time", c("t", "time"), sep = "_") %>%
  subset(select = -t)

> head(df.tidy)
#  episode time     value
#1       1    0 0.7466480
#2       2    0 0.7238865
#3       3    0 0.9024454
#4       4    0 0.7274303
#5       5    0 0.1932375
#6       6    0 0.1826925

现在,下面的代码创建了一个情节,其中 time = 1 和 time = 2 的行朝向剧集的开头不代表数据,因为 value 充满了 NA 和第一个数字条目在 value 中是时间 = 0.

ggplot(df.tidy, aes(x = episode, y = value, col = time)) +
  geom_point(alpha = 0.2) + 
  geom_line(aes(y = rollmean(value, 10, align = "right", fill = NA)))

我如何调整我的代码,使滚动平均线代表我的数据?

您的问题是您正在对整列应用移动平均值,这使得数据 "leak" 从一个值 time 变为另一个值。

您可以先 group_byrollmean 分别应用于每个时间:

ggplot(df.tidy, aes(x = episode, y = value, col = time)) +
  geom_point(alpha = 0.2) + 
  geom_line(data = df.tidy %>%
              group_by(time) %>%
              mutate(value = rollmean(value, 10, align = "right", fill = NA)))