如何使用时间序列图上的置信区间绘制实际值与预测值?

时间:2016-03-06 19:28:09

标签: r ggplot2

我很难(gg)绘制实际值与预测值。

这里有一些数据:

# I use caret in order to split the data into train and test
library(caret)
data(economics) # from caret
library(forecast)
# that is recommended for time series data
timeSlices <- createTimeSlices(1:nrow(economics), 
                       initialWindow = 36, horizon = 10, fixedWindow = TRUE)

 trainSlices <- timeSlices[[1]]
 testSlices <- timeSlices[[2]]

# I'm not really sure about the periods
fit <- tbats(economics[trainSlices[[1]],]$unemploy, seasonal.periods=c(4,12), use.trend=TRUE, use.parallel=TRUE)

# Using forecast for prediction
pred <- forecast(fit,h=length(economics[testSlices[[1]],]$unemploy))
# Here I plot the forecast
plot(pred)

enter image description here

这里我实际上卡住了,并且真的不知道如何将测试数据aka testSlices添加到具有相应测试/训练标签的特定pred对象。也许还有一种方法可以在置信区间使用不同的风格。 谢谢!

1 个答案:

答案 0 :(得分:2)

虽然有一种更清洁的方式。

快速做到这一点,就像这样:

lines(x = as.numeric(rownames(economics[testSlices[[1]],])), economics[testSlices[[1]],]$unemploy, col = "red")

评论更新:

添加标签:

legend(x = "topleft", legend = c("Predicted", "Test Data"), col = c("blue", "red"), lty = c(1, 1))

enter image description here