gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:32:02 28 4
gpt4 key购买 nike

我想用 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

现在,下面的代码创建了一个图,其中剧集开头的时间 = 1 和时间 = 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)))

Plot result

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

最佳答案

您的问题是您在整个列上应用移动平均值,这使得数据从时间的一个值“泄漏”到另一个值。

您可以首先group_by分别对每个时间应用rollmean:

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

enter image description here

关于R - 使用 ggplot2 在线图中绘制不同时间序列的滚动平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51580014/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com