forecast v7 and ggplot2 graphics

Version 7 of the forecast package was released on CRAN about a month ago, but I'm only just getting around to posting about the new features.

The most visible feature was the introduction of ggplot2 graphics. I first wrote the forecast package before ggplot2 existed, and so only base graphics were available. But I figured it was time to modernize and use the nice features available from ggplot2. The following examples illustrate the main new graphical functionality.

For illustration purposes, I'm using the male and female monthly deaths from lung diseases in the UK.

For all base plot() methods, there is now an autoplot() method with the same functionality.

library(forecast)
library(ggplot2)
 
# autoplot of a ts object
autoplot(mdeaths)

autoplot-1

# autoplot of a forecast object
fc <- forecast(fdeaths)
autoplot(fc)

autoplot-3

# autoplot of an stl object
autoplot(stl(mdeaths, s.window="periodic", robust=TRUE))

decomposition-1

# Plotting multiple forecasts in one plot
fmdeaths <- cbind(Males=mdeaths, Females=fdeaths)
fit <- tslm(fmdeaths ~ trend + season)
fcast <- forecast(fit, h=10)
autoplot(fcast)

unnamed-chunk-1-1

# Plotting the components of an ETS model
fit <- ets(mdeaths)
autoplot(fit)

unnamed-chunk-2-1

# Plotting the inverse characteristic roots of an ARIMA model
fit <- auto.arima(mdeaths, D=1)
autoplot(fit)

unnamed-chunk-3-1

For plotting functions that do not use an S3 plot() method, there is now a ggplot2 version with “gg” prefixed to the function name.

ggtsdisplay(mdeaths)
ggAcf(mdeaths, main="")
ggPacf(mdeaths, main="")
ggCcf(mdeaths, fdeaths)

acf-1

acf-2

acf-3

acf-4

ggseasonplot(mdeaths)
ggmonthplot(mdeaths)

seasonplot-1
seasonplot-2

There is also a new geom_forecast() function which uses forecast.ts() to obtain forecasts of the time series passed to autoplot().

autoplot(mdeaths) + geom_forecast(h=36, level=c(50,80,95))

unnamed-chunk-4-1

Almost all of this new gglot2 goodness was created by Mitchell O'Hara-Wild, a Monash University student who I employ as a research assistant.


Related Posts:


  • David Shaub

    Were any non-default arguments passed to autoplot() or the other functions to create these graphs? When I run this on my R session I’m getting much thinner lines with substantial aliasing. I created the attached picture with the code below:

    png(“seasonplot-1.png”, width = 576, height = 288)
    ggseasonplot(mdeaths)
    dev.off()

    • No. The graphs shown were produced using the commands in the post.

    • Jason

      Try a larger picture size and png format as above.

  • Jason

    Amazing work!! I always wanted to use ggplot2 with the forecast package, before it was a huge time sink. Thank you so much!