YCR YCR - 3 months ago 16
R Question

Automating htmlwidget: highchart graph generation for multiple time series

I would like to automate a graph generation using htmlwidget: highchart.

I get the manual process but I have difficulties to generalise it.
For two time series, it is ok, but I would like to extend to a number of time series(ts) not pre-determined.

I think about using brew to generate the code and using

source
, but it seems a bit the "heavy" solution.

Ideally, my input is a dataset with all the ts and with a vector of the time series I want to select.
The input is a hygraph with all the ts in my vector.

# dataset
dataset <- data.frame("Tokyo" = c(7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6)
, "London" = c(3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8)
, "Paris" = c(2.9, 1.2, 2.4, 5.4, 8.6, 10.2, 16.0, 15.6, 12.2, 7.3, 3.6, 2.8))

# sets:
set1 <- c("Tokyo", "Paris")


# only with set 1:

highchart() %>%
hc_series(
list(
name = "Tokyo",
data = c(7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6)
),
list(
name = "Paris",
data = c(2.9, 1.2, 2.4, 5.4, 8.6, 10.2, 16.0, 15.6, 12.2, 7.3, 3.6, 2.8)
)
)


# include n numbers of series, n undetermined (ex:3):
set <- c("Tokyo", "Paris", "London")

highchart() %>%
hc_series(
...
)

Answer

You can use the hc_add_series_list function :

# include n numbers of series, n undetermined (ex:3):
set <- c("Tokyo", "Paris", "London")

graph_data <- lapply(set, function(city) {
  list(name = city,
       data = dataset[[city]])
})

highchart() %>% 
  hc_add_series_list(graph_data)