Maksim.T Maksim.T - 1 year ago 235
Javascript Question

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

, but also a percentage of total amount of
yLabel (dataset1/(dataset1+dataset2))
I want to put this value in

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.

Answer Source

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 + " %";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download