在 R 中为时间序列图添加移动平均线

23

我在ggplot2软件包中有一组时间序列数据,并进行了移动平均操作,现在我想将移动平均的结果添加到时间序列图中。

数据集示例(p31):

ambtemp dt
-1.14 2007-09-29 00:01:57
-1.12 2007-09-29 00:03:57
-1.33 2007-09-29 00:05:57
-1.44 2007-09-29 00:07:57
-1.54 2007-09-29 00:09:57
-1.29 2007-09-29 00:11:57

用于呈现时间序列的代码:

  Require(ggplot2)
  library(scales)
  p29$dt=strptime(p31$dt, "%Y-%m-%d %H:%M:%S")
  ggplot(p29, aes(dt, ambtemp)) + geom_line() +
     scale_x_datetime(breaks = date_breaks("2 hour"),labels=date_format("%H:%M")) + xlab("Time 00.00 ~ 24:00 (2007-09-29)") + ylab("Tempreture")+
     opts(title = ("Node 29"))

时间序列展示样例 Sample of time series presentation

移动平均线图样例 enter image description here 预期结果样例

挑战在于时间序列数据来自包含时间戳和温度的数据集,而移动平均数据仅包括平均值列而不是时间戳。将这两者匹配可能导致不一致性。

Expected Results


3
请使您的示例可复现。 - Andrie
@Andrie,请问您能否解释一下您的意思?我想将移动平均线的图表添加到时间序列的图表中。 - A.Amidi
是的,那很明显。但您发布的代码在我的 R 会话中无法运行,因为您没有提供可重现的数据。如果我们可以运行您的代码,那么帮助您就变得容易得多了。 - Andrie
@Andrie,我添加了样本数据集并修改了代码。 - A.Amidi
1个回答

35

使用 zoo 库中的 rollmean() 函数来计算移动平均是一种解决方法。

由于您的问题中涉及数据框名称存在混淆(p31 和 p29),因此我将使用 p29。

p29$dt=strptime(p29$dt, "%Y-%m-%d %H:%M:%S")

library(zoo)
#Make zoo object of data
temp.zoo<-zoo(p29$ambtemp,p29$dt)

#Calculate moving average with window 3 and make first and last value as NA (to ensure identical length of vectors)
m.av<-rollmean(temp.zoo, 3,fill = list(NA, NULL, NA))

#Add calculated moving averages to existing data frame
p29$amb.av=coredata(m.av)

#Add additional line for moving average in red
ggplot(p29, aes(dt, ambtemp)) + geom_line() + 
  geom_line(aes(dt,amb.av),color="red") + 
  scale_x_datetime(breaks = date_breaks("5 min"),labels=date_format("%H:%M")) +
  xlab("Time 00.00 ~ 24:00 (2007-09-29)") + ylab("Tempreture")+
  ggtitle("Node 29")
如果需要在图例中显示线条颜色,则必须修改ggplot()中的aes()geom_line(),并添加scale_colour_manual()
  ggplot(p29, aes(dt)) + geom_line(aes(y=ambtemp,colour="real")) +
   geom_line(aes(y=amb.av,colour="moving"))+
   scale_x_datetime(breaks = date_breaks("5 min"),labels=date_format("%H:%M")) + 
   xlab("Time 00.00 ~ 24:00 (2007-09-29)") + ylab("Tempreture")+
   scale_colour_manual("Lines", values=c("real"="black", "moving"="red")) +    
   ggtitle("Node 29")

1
你也可以使用TTR包中的移动平均函数之一。 - Joshua Ulrich
@Didzis,如果您能告诉我如何将图例添加到图表中,以便呈现相应的时间序列和移动平均线,我将不胜感激。 - A.Amidi

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