User 6683331
User 6683331

Reputation: 710

Add lines to autoplot in R

I made a plot that predicts a time series. It was achieved wih this code:

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

Where 'ts' is a time series object. So I would like to add another time series to compare predicted values with actual values, starting from my last actual observation. I achieved it with a classical plot, adding a line with actual time series. This are the plots I have:

enter image description here enter image description here

How can I add this new line to my first plot?

Upvotes: 3

Views: 10625

Answers (1)

Rob Hyndman
Rob Hyndman

Reputation: 31820

Here is the simplest way to do it:

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

The autolayer command from the forecast package allows you to add layers involving time series and forecasts to existing plots.

Upvotes: 12

Related Questions