我正在尝试使用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}")
谢谢
答案 0 :(得分: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(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;
}")
)