How get sum of total values in stackedBar ChartJs

前端 未结 6 1540
执笔经年
执笔经年 2021-02-05 14:06

I\'m trying to get the sum of all values of a stackedBar and include this total in tooltip.

Note: my datasets aren\'t static, this is an example

6条回答
  •  逝去的感伤
    2021-02-05 14:46

    First you should know that if you return an array instead of a single string in the callback of the tooltip, it will display all the strings in your array as if it were different datasets (see this answer for more details).

    So I edited a little bit your callback to the following:

    callbacks: {
        label: function(tooltipItem, data) {
            var corporation = data.datasets[tooltipItem.datasetIndex].label;
            var valor = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
    
            // Loop through all datasets to get the actual total of the index
            var total = 0;
            for (var i = 0; i < data.datasets.length; i++)
                total += data.datasets[i].data[tooltipItem.index];
    
            // If it is not the last dataset, you display it as you usually do
            if (tooltipItem.datasetIndex != data.datasets.length - 1) {
                return corporation + " : $" + valor.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
            } else { // .. else, you display the dataset and the total, using an array
                return [corporation + " : $" + valor.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,'), "Total : $" + total];
            }
        }
    }
    

    You can see the full code in this jsFiddle, and here is its result :

提交回复
热议问题