【问题标题】:ggplot & Confidence Intervals for Holt-Winters Prediction FunctionHolt-Winters 预测函数的 ggplot 和置信区间
【发布时间】:2014-06-12 18:29:07
【问题描述】:

使用数据UKDriverDeaths

正在尝试使用 Holt-Winters 预测函数和ggplot()

基本上以置信区间 (2) 重现 ggplot (1) 中的数据。

这是数据:

data('UKDriverDeaths')    
past <- window(UKDriverDeaths, end = c(1982, 12))
hw <- HoltWinters(past)
pred <- predict(hw, n.ahead = 10)
plot(hw, pred, ylim = range(UKDriverDeaths))
lines(UKDriverDeaths)

这是在ggplot()中创建它的解决方案(1):

library(xts)
ts_pred <- ts(c(hw$fitted[, 1], pred), start = 1970, frequency = 12)
df <- merge(as.xts(ts_pred), as.xts(UKDriverDeaths))
names(df) <- c("predicted", "actual")
ggplot(df, aes(x=as.POSIXct(index(df)))) + 
  geom_line(aes(y=predicted), col='red') + 
  geom_line(aes(y=actual), col='black') + 
  theme_bw() +
  geom_vline(xintercept=as.numeric(as.POSIXct("1982-12-01")), linetype="dashed") + 
  labs(title="Holt-Winters filtering\n", x="Time", y="Observed / Fitted") + 
  theme(plot.title = element_text(size=18, face="bold"))

我正在寻找 holt-winters 预测的置信区间 (2)。

【问题讨论】:

  • 如果你这样做?predict.HoltWinters,你需要添加的两个参数来获得置信区间将会很明显。

标签: r ggplot2 prediction confidence-interval holtwinters


【解决方案1】:

通常,您将预测的置信区间称为“预测区间”。如果您使用prediction.interval=T 要求它们,predict.HoltWinters 函数将提供给您。所以你可以做

pred <- predict(hw, n.ahead = 10, prediction.interval = TRUE)

现在这将改变返回值的形状。您得到的不是一个简单的向量,而是一个矩阵,因此您需要调整一些其他转换代码来处理这个问题。试试

ts_pred <- ts(rbind(cbind(hw$fitted[, 1],upr=NA,lwr=NA), pred), 
    start = 1970, frequency = 12)
df <- merge(as.xts(UKDriverDeaths), as.xts(ts_pred))
names(df)[1:2] <- c("actual", "predicted")

这试图确保所有列在观察值和预测值之间正确排列和标记。

现在我们可以在图中添加两条线

ggplot(df, aes(x=as.POSIXct(index(df)))) + 
  geom_line(aes(y=predicted), col='red') + 
  geom_line(aes(y=actual), col='black') + 
  geom_line(aes(y=upr), col='blue') + 
  geom_line(aes(y=lwr), col='blue') + 
  theme_bw() +
  geom_vline(xintercept=as.numeric(as.POSIXct("1982-12-01")), 
      linetype="dashed") + 
  labs(title="Holt-Winters filtering\n", x="Time", y="Observed / Fitted") + 
  theme(plot.title = element_text(size=18, face="bold"))

【讨论】:

  • (+1) 对于预测周围的阴影区域,您可以使用geom_ribbon(aes(ymin=lwr,ymax=upr),alpha=0.3, fill="blue")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 2018-11-19
  • 1970-01-01
  • 1970-01-01
  • 2020-09-17
  • 2011-08-17
相关资源
最近更新 更多