Created
October 4, 2014 05:11
-
-
Save sinhrks/886b6c06bd6ba83ae5d3 to your computer and use it in GitHub Desktop.
Allow ggplot2 to handle forecast result
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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