Maksim.T
Maksim.T

Reputation: 541

Calculate value in tooltip in ChartJS

I'm using chartJS to display data with 2 or sometimes 3 datasets.

Can I make it so it shows not only tooltipItem.yLabel, but also a percentage of total amount of yLabel (dataset1/(dataset1+dataset2))? I want to put this value in afterLabel.

ChartJS options code:

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. X dataset is array of dates. I can't seem to figure out how chart.min.js takes these values.

Upvotes: 3

Views: 4119

Answers (2)

Maksim.T
Maksim.T

Reputation: 541

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 + " %";
},

Upvotes: 4

Kubilay Karpat
Kubilay Karpat

Reputation: 59

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.

Upvotes: 1

Related Questions