R Sankey Highchart:使用来自其他变量的数据来自定义节点工具提示

问题描述 投票:2回答:1

我正在尝试使用highcharter制作Sankey图,并且需要在节点工具提示中显示变量的总和,例如y。例如,对于节点“ A”,y的总和将为62(34 + 28)。

我已经尝试过了,但是不起作用

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}")

感谢

r tooltip sankey-diagram r-highcharter
1个回答
0
投票

下面的代码计算y的总和,并在工具提示中显示。

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(formatter = 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.point.a);
      var result = this.point.a + ' -> ' + this.point.b + 
                   '<br>Sum y: <b>' + sumy + '</b>';
      return result;
    }")
  )

enter image description here

节点工具提示的类似代码:

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;
  }")
) 
© www.soinside.com 2019 - 2024. All rights reserved.