Skip to content

Instantly share code, notes, and snippets.

@MarkEdmondson1234
Created June 18, 2014 21:29
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MarkEdmondson1234/3190fb967f3cbc2eeae2 to your computer and use it in GitHub Desktop.
Save MarkEdmondson1234/3190fb967f3cbc2eeae2 to your computer and use it in GitHub Desktop.
A function to plot a holtWinters timeseries in ggplot2
#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)
}
@MarkEdmondson1234
Copy link
Author

Demo of use:

myHWplot <- HWplot(your_time_series)

# output plot
myHWplot$p

# forecasted values
myHWplot$forecast

#fitted values
myHWplot$fitted

#your original data
myHWplot$actual

#the HW object for use in other functions
myHWplot$hwobject

@MarkEdmondson1234
Copy link
Author

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