Highcharter plotBands, plotLines with time series

2019-04-11 01:56发布

What is the correct way to specify values in highcharter library's plotLines and plotBands when plotting time series? With the following code, plot line appears at the left end of chart and band does not appear at all. If I don't specify type = 'stock' even the plot line does not appear. This seems to be a problem with time series data only as with other type of data it works fine. So I believe I may not be specifying the value in correct format. Besides the one in code, I have tried the time series format e.g. from = c(1990,1) but it did not work either.

library(highcharter)    
data =ts(data = sample(c(50:100),360, replace = TRUE), start = c(1987,1), frequency = 12, names = 'index')

highchart(type = 'stock')%>%
      hc_add_series_ts(data) %>%
      hc_xAxis(type = 'datetime',
               plotLines = list(
                 list(
                   label = list(text = "This is a plotLine"),
                   color = "#FF0000",
                   width = 5,
                   value = as.Date('1990-01-01', tz = 'UTC')
                   )
                 ),
                 plotBands = list(
                   list(
                     label = list(text = "This is a plotBand"),
                     color = "rgba(100, 0, 0, 0.1)",
                     from = as.Date('1995-01-01', tz = 'UTC'),
                     to = as.Date('1996-01-01', tz = 'UTC')
                     )
                   )
               )

This is the resulting chart enter image description here

标签: r highcharts
1条回答
叼着烟拽天下
2楼-- · 2019-04-11 02:21

All your date values need to be transformed using datetime_to_timestamp function.

This is, from :

 from = as.Date('1995-01-01', tz = 'UTC'),
 to = as.Date('1996-01-01', tz = 'UTC')

To:

 from = datetime_to_timestamp(as.Date('1995-01-01', tz = 'UTC')),
 to = datetime_to_timestamp(as.Date('1996-01-01', tz = 'UTC'))

Details:

suppressPackageStartupMessages(library(highcharter))
dt <- as.Date("1995-01-01", tz = "UTC")
dt
#> [1] "1995-01-01"
datetime_to_timestamp(dt)
#> [1] 788918400000

Hope this helps.

output

查看更多
登录 后发表回答