r - 将移动平均图添加到R中的时间序列图

标签 r ggplot2 add time-series moving-average

我在ggplot2软件包中有一个时间序列图,并且已经执行了移动平均,我想将移动平均值的结果添加到时间序列图中。

数据集样本(p31):

环境温度
-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"))

时间序列演示样本

移动平均图样本

预期结果样本

挑战在于,时间序列数据ov =从包含时间戳和温度的数据集中获取,而移动平均数据仅包含平均值列而不包含时间戳,而将这两者拟合会导致不一致。

最佳答案

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

在您的问题中(p31和p29)数据框名称有些困惑,因此我将使用p 29。

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

如果线条颜色应出现在图例中,则必须修改aes()ggplot()中的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")

关于r - 将移动平均图添加到R中的时间序列图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13840761/

相关文章:

r - 为什么在大型稀疏矩阵上的 R 行提取比将其分成较小的部分然后提取时要慢?

r - Ggplot2 方面 : put y-axis of the right hand side panel on the right side

减少范围ggplot y轴而不减少显示数据的范围

r - ggplot2 无法加载,出现 'rlang' 包错误

JavaScript 添加 hh :mm + hh:mm to get new hh:mm

visual-studio - 如何使用 AnkhSVN 将 VS2010 项目添加到 Google Code SVN?

r - 将带有美元符号 ($) 的变量与 facet_grid() 或 facet_wrap() 组合传递给 aes() 时出现问题

r - 使用separate()分割不同大小的字符串

java - 计算 Integer 值的每个数字的总和

r - 在 R 中的木星中隐藏代码