rr-highcharter

Customising hc_tooltip with formatter to add textcolor removed my markers and attempt to bring them back is failing


I am trying out the highcharter package in R. I am trying to add a tooltip. The default (first example) gives me a marker and the series name.

hc_tooltip(
      shared = TRUE,
      split = FALSE,
      valueDecimals = 2)

enter image description here

But when I try to to add text color to the tooltip to match the series color I lose the markers. My attempt below only yields the marker name but not the marker. Does anyone have a solution that works around my attempt?

hc<-hc %>% hc_tooltip(
    shared = TRUE,
    split = FALSE,
    valueDecimals = 2,
    symbol = "circle",
    formatter = JS(
      "function () {
        var tooltip = '<b>' + Highcharts.dateFormat('%Y-%m-%d', this.x) + '</b><br/>';
        $.each(this.points, function (i, point) {
          var color = point.series.color;
          var marker = point.series.symbol; // Get the marker symbol
          tooltip += '<span style=\"color:' + color + ';\"><b>' + marker + '</b>: '+ point.series.name + '</b>: ' + point.y.toFixed(2) + '</span><br/>';
        });
        return tooltip;
      }"
    )
  )

enter image description here


Solution

  • The default tooltip contains prepended spans for each series that take this form:

    <span style="color:rgb(161,173,255)">●</span>
    

    So you could add them to your tooltip something like this using a map to lookup the symbol code:

    library(highcharter)
    
    highchart() %>%
      hc_add_series(data = sample(1:12)) %>%
      hc_add_series(data = sample(1:12) + 10) %>%
      hc_tooltip(
        shared = TRUE,
        formatter = JS("
    function () {
        var tooltip = '<b>' + Highcharts.dateFormat('%Y-%m-%d', this.x) + '</b><br/>';
        
        $.each(this.points, function (i, point) {
            let symbolMap = new Map();
            symbolMap.set('circle',        '&#9679');
            symbolMap.set('diamond',       '&#9670');
            symbolMap.set('square',        '&#9632');
            symbolMap.set('triangle',      '&#9650');
            symbolMap.set('triangle-down', '&#9660');
        
            var color = point.series.color;
            var symbolName = point.series.symbol;
            
            tooltip += '<span style=\"color:' + color + ';\">' + symbolMap.get(symbolName) + '</span><span style=\"color:' + color + ';\">: '+ point.series.name + '</b>: ' + point.y.toFixed(2) + '</span><br/>';
        });
        return tooltip;
    }
    "
        )
      )