How can I have my forecast in ggplot ?

Hi ! I would like to have this forecast graph in ggplot2 to make it interractive with plotly but when I try ggplot(forecast1) I get this error message : Error: data must be a data frame, or other object coercible by fortify(), not an S3 object with class forecast

Can anyone explain me how I can do to fix it ?

My code below


library(ggplot2)
library(readxl)
library(forecast)

DensityPerYear <- read_xlsx("DensityPerYear.xlsx")

tsDensityPerYear <- ts(DensityPerYear$Density, frequency = 1, start = c(1970))

autoarima1 <- auto.arima(tsDensityPerYear)

forecast1 <- forecast(autoarima1, h=12)

plot(forecast1)

Here is a very rough beginning to reproducing in ggplot what is returned by plot(forecast1).

library(forecast)
library(ggplot2)

DensityPerYear <- data.frame(Year = 1970:2019, Density = sin((1:50)*pi/4))
tsDensityPerYear <- ts(DensityPerYear$Density, frequency = 1, start = c(1970))

autoarima1 <- auto.arima(tsDensityPerYear)

forecast1 <- forecast(autoarima1, h=12)
plot(forecast1)

NewDF <- data.frame(Year = 2020:2031, 
                    Mean =forecast1$mean, 
                    Lower = forecast1$lower, #forecast1$lower is a data frame with 2 col
                    Upper = forecast1$upper)
ggplot(data = NewDF) + geom_line(mapping = aes(Year, Mean)) +
  geom_line(mapping = aes(Year, Lower.80.)) +
  geom_line(mapping = aes(Year, Lower.95.)) +
  geom_line(mapping = aes(Year, Upper.80.)) +
  geom_line(mapping = aes(Year, Upper.95.)) +
  geom_line(mapping = aes(Year, Density), data = DensityPerYear)
#> Don't know how to automatically pick scale for object of type ts. Defaulting to continuous.

Created on 2020-03-22 by the reprex package (v0.3.0)

1 Like

The forecast package contains the autoplot() function which produces ggplot output rather than base plot output. So replace your plot() command with autoplot() and it should do what you want.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.