Created
June 18, 2014 21:29
-
-
Save MarkEdmondson1234/3190fb967f3cbc2eeae2 to your computer and use it in GitHub Desktop.
A function to plot a holtWinters timeseries in ggplot2
This file contains hidden or 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
#HWplot.R | |
library(ggplot2) | |
library(reshape) | |
HWplot<-function(ts_object, n.ahead=4, CI=.95, error.ribbon='green', line.size=1){ | |
hw_object<-HoltWinters(ts_object) | |
forecast<-predict(hw_object, n.ahead=n.ahead, prediction.interval=T, level=CI) | |
for_values<-data.frame(time=round(time(forecast), 3), value_forecast=as.data.frame(forecast)$fit, dev=as.data.frame(forecast)$upr-as.data.frame(forecast)$fit) | |
fitted_values<-data.frame(time=round(time(hw_object$fitted), 3), value_fitted=as.data.frame(hw_object$fitted)$xhat) | |
actual_values<-data.frame(time=round(time(hw_object$x), 3), Actual=c(hw_object$x)) | |
graphset<-merge(actual_values, fitted_values, by='time', all=TRUE) | |
graphset<-merge(graphset, for_values, all=TRUE, by='time') | |
graphset[is.na(graphset$dev), ]$dev<-0 | |
graphset$Fitted<-c(rep(NA, NROW(graphset)-(NROW(for_values) + NROW(fitted_values))), fitted_values$value_fitted, for_values$value_forecast) | |
graphset.melt<-melt(graphset[, c('time', 'Actual', 'Fitted')], id='time') | |
p<-ggplot(graphset.melt, aes(x=time, y=value)) + geom_ribbon(data=graphset, aes(x=time, y=Fitted, ymin=Fitted-dev, ymax=Fitted + dev), alpha=.2, fill=error.ribbon) + geom_line(aes(colour=variable), size=line.size) + geom_vline(x=max(actual_values$time), lty=2) + xlab('Time') + ylab('Value') + opts(legend.position='bottom') + scale_colour_hue('') | |
result.list <- list(plot = p, forecast = for_values, fitted = fitted_values, actual = actual_values, hwobject = hw_object) | |
return(result.list) | |
} |
I googled for the source as I copied it from somewhere, this looks like original https://github.com/Crytics/Forecasting/blob/master/HW_Forecast
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo of use: