简体   繁体   English

在ChartJS中计算工具提示中的值

[英]Calculate value in tooltip in ChartJS

I'm using chartJS to display data with 2 or sometimes 3 datasets. 我正在使用chartJS来显示2个或有时3个数据集的数据。

Can I make it so it shows not only tooltipItem.yLabel , but also a percentage of total amount of yLabel (dataset1/(dataset1+dataset2)) ? 我可以这样做,它不仅显示tooltipItem.yLabel ,还显示tooltipItem.yLabel总量的yLabel (dataset1/(dataset1+dataset2)) I want to put this value in afterLabel . 我想把这个值放在afterLabel

ChartJS options code: ChartJS选项代码:

tooltips : {

    callbacks : {

        label : function(tooltipItem, data) {
            return data.datasets[tooltipItem.datasetIndex].label + ': ' + tooltipItem.yLabel;
        },
        afterLabel : function(tooltipItem, data) {
            return dataset1/(dataset1+dataset2);
        },
    }
}

My 'Y' datasets are arrays of numbers. 我的'Y'数据集是数字数组。 X dataset is array of dates. X数据集是日期数组。 I can't seem to figure out how chart.min.js takes these values. 我似乎无法弄清楚chart.min.js如何获取这些值。

I managed to do what I wanted, thank you @Kubilay Karpat for bringing me to an idea how to find needed values. 我设法做了我想做的事,感谢@Kubilay Karpat让我了解如何找到所需的价值观。 I would +rep you, but I don't have enough to do so. 我会代表你,但我没有足够的能力。

afterLabel : function(tooltipItem, data) {
    var total = 0;
    total = parseInt(data.datasets[0].data[tooltipItem.index]) + parseInt(data.datasets[1].data[tooltipItem.index]);                    
    var percentage = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index] / total * 100;
    var percentage = percentage.toFixed(2);
    return percentage + " %";
},

Yes you can. 是的你可以。 All you need to do is traverse all datasets and sum the values that corresponds your index number. 您需要做的就是遍历所有数据集并将与索引号对应的值相加。 Then you can divide your number to this sum. 然后你可以将你的数字除以这个总和。 Following code works for me: 以下代码适用于我:

afterLabel: function(tooltipItem, data){
  var total = 0;
  for (i = 0; i < data.datasets.length; i++) {
    total += data.datasets[i].data[tooltipItem.datasetIndex];
  }
  var percentage = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index] / total * 100;
  var percentage = percentage.toFixed(2); // Trim decimal part
  return "Percentage: %" + percentage;
}

Also, following part seems like redundant, since this the default pattern of tooltip label. 此外,以下部分似乎是多余的,因为这是工具提示标签的默认模式。

label : function(tooltipItem, data) {
        return data.datasets[tooltipItem.datasetIndex].label + ': ' + tooltipItem.yLabel;
    },

And if you like to trim/floor/ceil the percentage like in my example you might want to consider the fact that sums of percentages might not be equal to 100 in your graph. 如果你喜欢在我的例子中修剪/下限/ ceil百分比,你可能想要考虑图表中百分比之和可能不等于100的事实。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM