向 Dygraph 添加预测

Add Prediction to Dygraph

我正在学习以下教程:

https://rstudio.github.io/dygraphs/

他们在底部显示了一个预测,我想将其添加到原始时间序列图中。下面是代码,我不确定如何将两者结合起来:

install.packages("dygraphs")
library(dygraphs)
library(forecast)
library(dplyr)

dygraph(ldeaths)

然后我做了一个预测:

hw <- HoltWinters(ldeaths)
predicted <- predict(hw, n.ahead = 72, prediction.interval = TRUE)

dygraph(predicted, main = "Predicted Lung Deaths (UK)") %>%
  dyAxis("x", drawGrid = FALSE) %>%
  dySeries(c("lwr", "fit", "upr"), label = "Deaths") %>%
  dyOptions(colors = RColorBrewer::brewer.pal(3, "Set1"))

如何将两者合二为一?

似乎这个库需要您合并数据,然后将单独的系列 "layers" 添加到绘图中。使用您的示例,您可以这样做:

# combine the time series actual and forcasted values
combined <- cbind(predicted, actual=ldeaths)

# plot the different values as different series    
dygraph(combined , main = "Predicted Lung Deaths (UK)") %>%
  dyAxis("x", drawGrid = FALSE) %>%
  dySeries("actual", label = "actual") %>%
  dySeries(paste0("predicted.", c("lwr", "fit", "upr")), label = "Predicted") %>%
  dyOptions(colors = RColorBrewer::brewer.pal(3, "Set1"))