Skip to content

Instantly share code, notes, and snippets.

@sinhrks
Created October 4, 2014 05:11
Show Gist options
  • Save sinhrks/886b6c06bd6ba83ae5d3 to your computer and use it in GitHub Desktop.
Save sinhrks/886b6c06bd6ba83ae5d3 to your computer and use it in GitHub Desktop.
Allow ggplot2 to handle forecast result
library(forecast)
library(ggplot2)
d <- AirPassengers
d.arima <- forecast::auto.arima(d)
d.forecast <- forecast(d.arima, level = c(95), h = 50)
fortify.forecast <- function(forecast.data) {
require(dplyr)
forecasted <- as.data.frame(forecast.data)
forecasted$Time <- as.Date(time(forecast.data$mean))
fitted <- data.frame(Time = as.Date(time(forecast.data$fitted)),
Original = forecast.data$x,
Fitted = forecast.data$fitted)
rownames(fitted) <- NULL
rownames(forecasted) <- NULL
dplyr::rbind_list(fitted, forecasted)
}
head(ggplot2::fortify(d.forecast))
ggplot(data = d.forecast) +
geom_line(mapping = aes_string(x = 'Time', y = 'Original')) +
geom_line(mapping = aes_string(x = 'Time', y = '`Point Forecast`'), colour='blue') +
geom_ribbon(mapping = aes_string(x = 'Time', ymin = '`Lo 95`', ymax = '`Hi 95`'), alpha = 0.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment