A.A*_*idi 20 r add time-series moving-average ggplot2
我在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"))
Run Code Online (Sandbox Code Playgroud)
时间序列演示的样本
移动平均线图样本
预期结果的样本
挑战在于时间序列数据ov =从数据集中获得,其中包括时间戳和温度,但移动平均数据仅包括平均列而不是时间戳,并且拟合这两者可能导致不一致.
Did*_*rts 32
一种解决方案是使用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")
Run Code Online (Sandbox Code Playgroud)
如果线的颜色应该出现在图例,然后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")
Run Code Online (Sandbox Code Playgroud)