R dygraph预测与原始值一起绘制

时间:2015-10-14 09:18:23

标签: r time-series dygraphs

我需要在Dygraphs中绘制一个时间序列,其中多个时间序列一起绘制。

我们可以使用

作为数据
df <- cbind(mdeaths, fdeaths)

在dygraphs网站上完成:https://rstudio.github.io/dygraphs/

但是我想让两个时间序列的预测在与原始数据相同的图像中继续。我粗略地描绘了我想要实现的目标

enter image description here

一种方法当然是单独使用auto.arima进行预测,然后再次组合数据。我想知道是否有功能,可以一次完成所有功能吗?

2 个答案:

答案 0 :(得分:0)

我认为您的意思在同一网站的“上/下栏”部分得到解答:https://rstudio.github.io/dygraphs/gallery-upper-lower-bars.html。 您需要制作预测模型,例如:

hw <- HoltWinters(mdeaths)
p <- predict(hw, n.ahead = 36, prediction.interval = TRUE)
all <- cbind(ldeaths, p)

并绘制de graph:

dygraph(all, "Deaths from Lung Disease (UK)") %>%
  dySeries("mdeaths", label = "Actual") %>%
  dySeries(c("p.lwr", "p.fit", "p.upr"), label = "Predicted")

答案 1 :(得分:0)

一个简单的解决方案是:

hw <- HoltWinters(mdeaths)
predictedMen <- predict(hw, n.ahead = 12 ,prediction.interval = TRUE)
hw <- HoltWinters(fdeaths)
predictedWomen <- predict(hw, n.ahead = 12 ,prediction.interval = TRUE)
predictedMen %>%  class
AuxF <- function(x){
  x <- data.frame(date=  as.Date(x), Vuelos=as.matrix(x) )
  x <- read.zoo(x, format = "%Y-%m-%d")
  return(x)
}
DF <- zoo( 
  cbind(
rbind( cbind( upr = AuxF(mdeaths), fit= AuxF(mdeaths) ,  lwr = AuxF(mdeaths)) 
   ,  cbind( upr = AuxF(predictedMen[ , 2]), fit= AuxF(predictedMen[ , 1]) ,  lwr = 
AuxF(predictedMen[ , 3])) )
, rbind( cbind( upr = AuxF(fdeaths), fit = AuxF(fdeaths) ,  lwr = AuxF(fdeaths)) 
     ,  cbind( upr = AuxF(predictedWomen[ , 2]), fit = AuxF(predictedWomen[ , 1]) ,  
wr = AuxF(predictedWomen[ , 3])) ) 
) )    
names(DF) <- c("predictedMen.upr", "predictedMen.fit", "predictedMen.lwr",
"predictedWomen.upr", "predictedWomen.fit", "predictedWomen.lwr")
dygraph(DF, main = "Predicted Lung Deaths (UK)") %>%
dyAxis("x", drawGrid = FALSE) %>%
  dySeries(c("predictedMen.upr", "predictedMen.fit", "predictedMen.lwr"), label = 
"Men")
%>%   dySeries(c("predictedWomen.upr", "predictedWomen.fit", "predictedWomen.lwr"),
label = "Women") %>% 
  dyOptions(colors = RColorBrewer::brewer.pal(3, "Set1"))  %>%
  dyRangeSelector(height = 200)