How get sum of total values in stackedBar ChartJs

前端 未结 6 1525
执笔经年
执笔经年 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:43

    Using Chart.js 2.5.0

    var valor = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
    

    returns a string value. To calculate the correct sum value you have to add a parseFloat statement:

        tooltips: {
                mode: 'label',
                callbacks: {
                    afterTitle: function() {
                        window.total = 0;
                    },
                    label: function(tooltipItem, data) {
                        var corporation = data.datasets[tooltipItem.datasetIndex].label;
                        var valor = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
    
                          //THIS ONE:
                        valor=parseFloat(valor);
    
            window.total += valor;
                        return corporation + ": " + valor.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");             
                    },
                    footer: function() {
                        return "TOTAL: " + window.total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    
                    }
                }
            }
    

提交回复
热议问题