Add tooltip after hc_add_series in HighcharteR

36 Views Asked by At

I need to create a chart with some boxplots and a scatter with tooltip on the scatter (JS function). Then I export the result with hc_export() in order to use it with highcharts-export-server.

The actual code is (not real code...) :

myboxplot <- highchart() %>%
    # add all my boxplots
    hc_add_series_list(myboxplotData) %>%
    # add a scatter
    hc_add_series( data = mydf,
        type = "scatter",
        hcaes(x = "label", y = "value", group = "label"),
        # add tooltip to scatter
        tooltip=list(headerFormat="",pointFormatter= JS("function(){
            return('<strong><i>Sample : ' +
            this.name_sample +
            '</i><br>Expression : ' + Math.round((this.value + Number.EPSILON) * 1000) / 1000 +
            '<br>Description : ' + this.description
            '</strong>')}"))
    ) 
# export the chart
export_hc(myboxplot, filename = paste0("/tmp/hc_boxplot.js"), as = "is")

It works well but the problem is if I want to use the hc_boxplot.js file in highcharts-export-server, I have to remove the JS part (the scatter tooltip) otherwise it throws an error.

So I need to add the tooltip AFTER the export_hc() function, something like this :

myboxplot <- highchart() %>%
    # add all my boxplots
    hc_add_series_list(myboxplotData) %>%
    # add a scatter
    hc_add_series( data = mydf,
        type = "scatter",
        hcaes(x = "label", y = "value", group = "label")
    ) 
# export the chart
export_hc(myboxplot, filename = paste0("/tmp/hc_boxplot.js"), as = "is")
# add the tooltip
myboxplot <- myboxplot %>%
    # add tooltip to scatter
        hc_tooltip=(headerFormat="",pointFormatter= JS("function(){
            return('<strong><i>Sample : ' +
            this.name_sample +
            '</i><br>Expression : ' + Math.round((this.value + Number.EPSILON) * 1000) / 1000 +
            '<br>Description : ' + this.description
            '</strong>')}")

This add the tooltip to the scatter BUT it removes the tooltip on my boxplot (not shown). How to access to the scatter serie only ? Thanx

1

There are 1 best solutions below

0
Fabrice On

I found by myself by printing (view) the R boxplot object in Rstudio.

Using a loop over each element of the serie we can set the values for the tooltip.

mypointformatter <- "function(){return('<strong><i>Sample : ' + this.name_sample + '</i><br>Expression : ' + Math.round((this.value + Number.EPSILON) * 1000) / 1000 + '<br>Description : ' + this.description + '<br>pTNM : ' + this.pTNM + '<br>Grade : ' + this.grade + '<br>Statut MRES : ' + this.statut_MRES + '<br>Statut Basal-like : ' + this.statut_basal + '</strong>')}"
class(mypointformatter) = "JS_EVAL"
for (serie in seq(first_elt_index, last_elt_index,1) ) {
    myboxplot[["x"]][["hc_opts"]][["series"]][[serie]][["tooltip"]][["headerFormat"]] = ""
    myboxplot[["x"]][["hc_opts"]][["series"]][[serie]][["tooltip"]][["pointFormatter"]] = mypointformatter
}