r - 在 R 中向自动绘图添加线条

标签 r plot ggplot2 time-series

我做了一个预测时间序列的图。这是通过以下代码实现的:

forecast1 <- HoltWinters(ts, beta = FALSE, gamma = TRUE) 
forecast2 <- forecast(forecast1, h = 60)    
autoplot(forecast2)

其中“ts”是时间序列对象。
所以我想添加另一个时间序列来比较预测值和实际值,从我最后一次实际观察开始。我用经典情节实现了它,添加了一条具有实际时间序列的线。这是我的情节:

enter image description here
enter image description here

如何将这条新线添加到我的第一个图中?

最佳答案

这是最简单的方法:

library(ggplot2)
library(forecast)

smpl1 <- window(AirPassengers, end = c(1952, 12))
smpl2 <- window(AirPassengers, start = c(1953, 1), end = c(1953,12))

hw       <- HoltWinters(smpl1, beta = FALSE, gamma = TRUE) 
forecast <- forecast(hw, h = 12)  

autoplot(forecast) +
  autolayer(smpl2, series="Data") +
  autolayer(forecast$mean, series="Forecasts")

enter image description here
autolayer来自预测包的命令允许您将涉及时间序列和预测的图层添加到现有绘图中。

关于r - 在 R 中向自动绘图添加线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47454063/

相关文章:

R 和 rect.hclust : rectangle on labels in dendrograms

r - R中的NSLOOKUP(rstats)

r - scale_x_date (ggplot) 中的限制参数仍然产生 data.frame 范围之外的日期

R:如何使用任意基数在 ggplot2 中创建对数刻度?

python - Enthought + PyCharm - 无法再显示绘图

plot - 在 Julia 中,绘制具有特定子标签的图形

r - 如何在 ggplot geom_tile 中正确使用构面,同时保持纵横比不变?

r - Shiny - FILL 值未在 Shiny 服务器中正确传递给 ggplot - 未找到错误对象 'input'

r - stringr 的字符串操作无法根据向量化/非向量化调用进行工作

r - ggplot2 label out of the graph in likert scale