Search code examples
rtooltipsankey-diagramr-highcharter

R Sankey Highchart: customizing node tooltip using data from a different variable


I'm trying to make a Sankey diagram with highcharter and I need to show in the node tooltip the sum of a variable, say y. For instance, for node "A" the sum of y would be 62 (34+28).

I have tried this but it won't work

test <- data.frame(a = c("A", "B", "A", "B"), 
                   b = c("C", "C", "D", "D"), 
                   x = c(4, 9, 2, 2), 
                   y = c(34, 29, 28, 26)) 

hchart(test, "sankey", nodeWidth = 10, hcaes(from = a, to = b, weight = x)) %>% 
 hc_tooltip(nodeFormat = "{y.sum}")

Thanks


Solution

  • The code below calculates the sum of y and shows it in the tooltip.

    library(highcharter)    
    test <- data.frame(a = c("A", "B", "A", "B"), 
                       b = c("C", "C", "D", "D"), 
                       x = c(4, 9, 2, 2), 
                       y = c(34, 29, 28, 26))   
    
    hchart(test, "sankey", nodeWidth = 10, hcaes(from = a, to = b, weight = x)) %>% 
      hc_tooltip(nodeFormatter = JS("
        function() {
          // Function for y sum calculation
          function getSum(arr, val) {
            var idx = [], i, sumy=0;
            for (i = 0; i < arr.length; i++) {
              if (arr[i].from==val | arr[i].to==val) {
                sumy = sumy + arr[i].y
              }
            }
            return(sumy)
          }
          // Get y sum and show it in the tooltip       
          sumy = getSum(this.series.options.data, this.name);
          var result = 'Node: ' + this.name + 
                       '<br>Sum y: <b>' + sumy + '</b>';
          return result;
        }")) %>%
      hc_tooltip(pointFormatter = JS("
        function() {
          // Function for y sum calculation
          function getSum(arr, val) {
            var idx = [], i, sumy=0;
            for (i = 0; i < arr.length; i++) {
              if (arr[i].a==val) {
                sumy = sumy + arr[i].y
              }
            }
            return(sumy)
          }
          // Get y sum and show it in the tooltip       
          sumy = getSum(this.series.options.data, this.from);
          var result = this.from + ' -> ' + this.to + 
                       '<br>Sum y: <b>' + sumy + '</b>';
          return result;
        }")
      ) 
    

    enter image description here