0

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(
  ...      
  )
YCR
  • 3,794
  • 3
  • 25
  • 29

2 Answers2

3

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)
Tutuchan
  • 1,527
  • 10
  • 19
  • Thanks, I wasn't aware of that function. I was using the v0.3.0 in which the function was not yet implemented. Just upgraded to v0.4.0 and found it. Awesome, thanks. – YCR Aug 22 '16 at 13:31
0

I have solve my issue using an expression:

the following code works:

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

sets.tab <- lapply(set, function(x) paste0("list(name = '", x, "', data = dataset[, '"
                    , x, "'])"))

no.parsed.expr <- paste0(sets.tab, collapse = "
                     , ")
end.code <- paste0("highchart() %>%  
  hc_series(", no.parsed.expr, ")")

eval(parse(text = end.code))
YCR
  • 3,794
  • 3
  • 25
  • 29