如何将时间序列图添加到常规图?

时间:2019-05-27 18:36:19

标签: r ggplot2 time-series

我对时间序列进行了移动平均,我想将其叠加在时间序列之上。

这是我的系列ggplot(daily_revenue, aes(day, revenue)) + geom_line()

enter image description here

这是我的移动平均线ma(ts(daily_rev_full$revenue, start = c(2014, 1), frequency = 365), order = 15) %>% autoplot()

enter image description here

我试图通过将它们包括为单独的geom_line值来将它们添加在一起。我还尝试将自动绘图添加到ggplot中,并尝试创建一个常规绘图,然后使用lines()添加移动平均值。

2 个答案:

答案 0 :(得分:1)

在这种情况下,

TTR 可用于更有效地生成移动平均值。

例如,假设生成了100个随机数,并生成了30个周期的简单移动平均值。

numbers<-rnorm(100)

#SMA
library("TTR")
simplemovingaverage<-SMA(numbers,n=30)
plot(numbers,type='l',col='blue',xlab="X",ylab="Y")
lines(simplemovingaverage,type='l',col='red')
title("Numbers")

使用图来绘制实际值,并使用线来绘制SMA,这是生成的图:

sma

答案 1 :(得分:0)

使用forecast包,您可以使用autoplot()生成时间序列对象图。为了叠加您的移动平均线,您可以使用autolayer()函数。请参阅下面的reprex。

library(forecast)

autoplot(WWWusage) +
  autolayer(ma(WWWusage, order = 10), colour = TRUE)
#> Warning: Removed 10 rows containing missing values (geom_path).

reprex package(v0.2.1)于2019-05-28创建