使用R中的dygraph可视化每日时间序列数据

时间:2017-07-11 04:43:46

标签: arrays r time-series dygraphs timeserieschart

我的数据框类似于'df1'。将值列转换为每日时间序列后,我适合使用Holt Winters方法并预测将来120天。我希望能够使用dygraph可视化实际和预测。

library(dygraphs)
> head(df1)
   timestamp   value
1 2017-03-29   534.4571
2 2017-03-30   536.4350
3 2017-03-31   534.6661
4 2017-04-01   535.9185
5 2017-04-02   532.6998
6 2017-04-03   534.8282

convert_to_daily_ts <- function(x){
  x <- x[order(x$timestamp),]
  x$value_ts <- ts(x$value, frequency = 7)
  return(x)
}

df1 <- convert_to_daily_ts(df1)

hw <- tryCatch(HoltWinters(df1$value_ts), error=NA)
p <- predict(hw, n.ahead = 120, prediction.interval = TRUE, level=0.95)

act <- df1$value_ts
all <- cbind(act, p)

> class(all)
[1] "mts"    "ts"     "matrix"

> head(all)
Time Series:
Start = c(1, 1)
End = c(1, 6)
Frequency = 7
           actual p.fit p.upr p.lwr
1.000000 534.4571    NA    NA    NA
1.142857 536.4350    NA    NA    NA
1.285714 534.6661    NA    NA    NA
1.428571 535.9185    NA    NA    NA
1.571429 532.6998    NA    NA    NA
1.714286 534.8282    NA    NA    NA


> tail(all)
Time Series:
Start = c(115, 2)
End = c(115, 7)
Frequency = 7
         actual    p.fit    p.upr    p.lwr
115.1429     NA 386.2924 581.7568 190.8279
115.2857     NA 384.4614 580.0625 188.8603
115.4286     NA 383.4728 579.2104 187.7352
115.5714     NA 381.3159 577.1900 185.4418
115.7143     NA 383.3130 579.3234 187.3025
115.8571     NA 384.2098 580.3565 188.0631

 > str(all)
 mts [1:805, 1:4] 534 536 535 536 533 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:4] "actual" "p.fit" "p.upr" "p.lwr"
 - attr(*, "tsp")= num [1:3] 1 116 7
 - attr(*, "class")= chr [1:3] "mts" "ts" "matrix"

dygraph(all, main = "Daily Predictions") %>%
        dySeries("act", label = "Actual") %>%
        dySeries(c("p.lwr", "p.fit", "p.upr"), label = "Predicted") %>%
        dyOptions(drawGrid = F) %>%
        dyRangeSelector()

我得到Error:Unsupported type passed to argument 'data'.但是'all'的类与dygraph的预期相同。任何可视化上述数据(实际和预测)的帮助都会有所帮助。此外,我需要x轴值显示月 - 年(例如:2017年6月,2017年7月),而不是1,2,3等。有可能吗?

1 个答案:

答案 0 :(得分:0)

看起来ts对象需要dygraph的开始和结束日期来解决问题。你可以在创建ts对象时添加适当的开始和结束日期吗?您需要根据需要调整开始日期和结束日期。有关于here的帖子。

convert_to_daily_ts <- function(x){
  x <- x[order(x$timestamp),]
  x$value_ts <- ts(x$value, start = c(2017,3), end = c(2017,7), frequency = 7)
  return(x)
}
相关问题