Search code examples
rdygraphs

Add Prediction to Dygraph


I am following the tutorial from:

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

They show a prediction at the bottom and I want to add it to the original time series graph. So below is the code and I am not sure how to combine the two:

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

dygraph(ldeaths)

enter image description here

Then I made a prediction:

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"))

enter image description here

How do I combine the two into one graph?


Solution

  • Seem this library requires you to combine the data and then add separate series "layers" to the plot. With your example you could do this:

    # 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"))
    

    enter image description here