Search code examples
rlisthighchartsr-highcharter

define x values for hc_add_series_list in highcharter


I want to define the x-values for a highcharter line plot, as I have categorial x-values and also sometimes values which refer to the same categorie. Anyway on highcharter it is possible as in this example on 15th of December shows: https://whatukthinks.org/eu/questions/should-the-united-kingdom-remain-a-member-of-the-eu-or-leave-the-eu/?removed . With the function hc_add_series I'm able to define the x values as you can see in the example below:

library(highcharter)
df = data_frame(x = c(1,1,3,3,5:7),y = c(100,105,110,120,80,90,98),name = 
c("A","A","A","A","B","B","B"))

hc2 <- highchart() %>%
    hc_add_series(df)

hc2

In my case, I don't know how many series there will be in the begin, so I want to use hc_add_series_list as I can define the list beforehand. But then I can't define the x-value, as data is always interpreted as the y value. after I read https://dantonnoriega.github.io/ultinomics.org/post/2017-04-05-highcharter-explainer.html I think it should be possible with sublists, but until now I'm not really sucessfull. I tried it like that:

ds_new <- lapply((1:1), function(x){
  list(name = paste(trips_of_choice[x]),
       data = list(x = c(1:2),
                   y = c(1:2),
                   name =c("5.TA.26-3-j19-1.5.R")
       ))
})

So to have a list with sublists which is named data and include x and y data. But it doesn't work at all.

I hope someone can help me here


Solution

  • Suppose your series are stored in a list:

    df1 <- data.frame(x = c(1,2,3,4),
                      y = c(100,105,110,120),
                      name = c("A","A","A","A"))
    df2 <- data.frame(x = c(3:6),
                      y = c(80,90,98,105),
                      name = c("B","B","B","B"))
    series_list <- list(df1, df2)
    

    You can plot all the series using this solution:

    hc2 <- highchart()
    for (k in 1:length(series_list)) {
       hc2 <- hc2 %>%
              hc_add_series(series_list[[k]])
    }
    hc2
    

    enter image description here