[Chartjs]-Calculate value in tooltip in ChartJS

4πŸ‘

βœ…

I managed to do what I wanted, thank you @Kubilay Karpat for bringing me to an idea how to find needed values. 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 + " %";
},

1πŸ‘

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.

Leave a comment