Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
738 views
in Technique[技术] by (71.8m points)

r - Highcharter plotBands, plotLines with time series data

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...