Home > OS >  plotting time series forecast with ggplot
plotting time series forecast with ggplot

Time:06-22

I have the following time series and base R code that plots it along with its forecast. I want to recreate the plot using ggplot but I'm not sure how.

timeseries = ts(c(426, 386, 417, 448, 466, 418, 530, 587, 709, 751, 888, 834, 857, 847), 
start=2008, end=2021, frequency=1)

fit=auto.arima(timeseries)

forecast = forecast(fit, h=4, level=95)

plot(forecast, main= 'forecast (95%)', col='black', type='b', lwd='1.4')

enter image description here

Plotting the actual time series is easy, but I don't know how to add the forecast along with the confidence interval.

df=data.frame(year=2008:2021, timeseries=timeseries)

ggplot(data=df, aes(x=year, y=timeseries))  
  geom_line()

enter image description here

CodePudding user response:

Try this:

library(tidyverse)
library(forecast)
library(timetk)

# Supplied data
timeseries = ts(c(426, 386, 417, 448, 466, 418, 530, 587, 709, 751, 888, 834, 857, 847), 
                start=2008, end=2021, frequency=1)

fit=auto.arima(timeseries)

forecast = forecast(fit, h=4, level=95)

# ggplot approach
fc_df <- forecast |> 
  as_tibble() |> 
  mutate(index = 2022:2025)

timeseries |> 
  tk_tbl() |> 
  bind_rows(fc_df) |> 
  ggplot(aes(index, value))  
  geom_line()  
  geom_point(shape = 21)  
  geom_ribbon(aes(ymin = `Lo 95`, ymax = `Hi 95`), fill = "grey80")  
  geom_point(aes(y = `Point Forecast`), colour = "blue")  
  labs(title = "Forecast (95%)")

Created on 2022-06-21 by the reprex package (v2.0.1)

  • Related