简体   繁体   中英

visualise daily time series data using dygraphs in R

I have a dataframe similar to 'df1'. After Converting the value column to a daily time series, I fit using Holt Winters method and predict 120 days in the future. I want to be able to visualise the actual and predicted using dygraphs.

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

I get Error:Unsupported type passed to argument 'data'. But the class of 'all' is as expected for the dygraph. Any help to visualise above data(actual & predicted) will be helpful. Also, I need the x-axis values to show month-year(Ex: Jun 2017, Jul 2017) instead of 1,2,3 so on. Is it possible ?

It looks like the ts object needs start and end dates for dygraph to figure things out. Could you add the appropirate start and end dates when you create the ts object? You'll need to adjust the start and end dates as appropriate. There's a post about that 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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM