16

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

var barChartData = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [{
            label: 'Corporation 1',
            backgroundColor: "rgba(220,220,220,0.5)",
            data: [50, 40, 23, 45, 67, 78, 23]
        }, {
            label: 'Corporation 2',
            backgroundColor: "rgba(151,187,205,0.5)",
            data: [50, 40, 78, 23, 23, 45, 67]
        }, {
            label: 'Corporation 3',
            backgroundColor: "rgba(151,187,205,0.5)",
            data: [50, 67, 78, 23, 40, 23, 55]
        }]

    };

    window.onload = function() {
        var ctx = document.getElementById("canvas").getContext("2d");
        window.myBar = new Chart(ctx, {
            type: 'bar',
            data: barChartData,
            options: {
                title:{
                    display:true,
                    text:"Chart.js Bar Chart - Stacked"
                },
                tooltips: {
                    mode: 'label',
                    callbacks: {
                       label: function(tooltipItem, data) {
                       var corporation = data.datasets[tooltipItem.datasetIndex].label;
                       var valor = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
                       var total = eval(data.datasets[tooltipItem.datasetIndex].data.join("+"));
                       return total+"--"+ corporation +": $" + valor.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                  }
                    }
                },
                responsive: true,
                scales: {
                    xAxes: [{
                        stacked: true,
                    }],
                    yAxes: [{
                        stacked: true
                    }]
                }
            }
        });
    };

Now total is the sum per dataset and I need the sum per stackedBar.

Example

Label A: value A

Label B: value B

Label C: value C

TOTAL: value A + value B + value C

It is possible to get that total value?

Thanks, Idalia.

1
  • 1
    Rather than a tooltip, can I have it as text in the chart itself so it can be printed out?
    – sureshvv
    Jun 4, 2021 at 5:47

8 Answers 8

25

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 :

enter image description here

6
  • 1
    thanks so much @Tektiv , this solve my problem, Important Note: I had a problen between versions of chart.js so I changed to chart.js 2.2.1 and then works well, thanks again!
    – Idalia
    Sep 7, 2016 at 17:44
  • its possible to hide total legend?
    – Haider
    Jul 24, 2017 at 22:16
  • @Haider Sure ! You just need to add display: false in the legend options, like this
    – tektiv
    Jul 24, 2017 at 23:05
  • @tektiv i meant in the tooltip , sorry for not asking question properly
    – Haider
    Jul 25, 2017 at 5:55
  • @Haider Do you mean hiding the tooltip ?
    – tektiv
    Jul 25, 2017 at 12:04
25

i modified tektiv answer to show Total only for active sets and move it to tooltips footer.

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];
                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, " ");
            }
        }
    }
3
  • 4
    I prefer this solution because the "total" entry doesn't get colored box next to it. That better reflects the chart data since we don't graph the total as a separate data set. Jun 22, 2018 at 16:18
  • 1
    Should be the preferred solution. Apr 29, 2019 at 9:31
  • in another dev context I have error TS2339: Property 'total' does not exist on type 'Window'
    – Pipo
    Jun 18, 2019 at 16:22
12

Shorter version of Gaspar's answer:

tooltips: {
  callbacks: {
    footer: (tooltipItems, data) => {
      let total = tooltipItems.reduce((a, e) => a + parseInt(e.yLabel), 0);
      return 'Total: ' + total;
    }
  }
}

Example: https://jsfiddle.net/g3ba60zc/2/ Tooltip with total

1
  • 1
    the best solution for my use case. thank you very much
    – lorenzo
    Jun 17, 2020 at 13:33
11

In the other answers you replace the last dataset, with this you don't need to

tooltips: {
    callbacks: {
        title: function(tooltipItems, data) {
            return _this.chart.data.labels[tooltipItems[0].index];
        },
        footer: function(tooltipItems, data) {
            let total = 0;
            for (let i = 0; i < tooltipItems.length; i++) {
                total += parseInt(tooltipItems[i].yLabel, 10);
            }
            return 'Total: ' + total;
        }
    }
}

Ps: It's typescript lang.

4
  • 1
    Best way to not store any data in window like other answers. Title callback is actually not needed if you don't want to modify this, by default it shows the correct label.
    – CularBytes
    Feb 7, 2019 at 17:01
  • @CularBytes: I totally disagree... This solution works only if you have (Like the OP) nothing else than numbers in your labels (yLabel). Apr 29, 2019 at 9:31
  • @FranzHuber23 of course you have some pre- and pos- checking todo, also when switching around numbers to y-axes or something. But storing in window makes sure you cannot re-use a function for multiple graphs, because you would obviously sum all values of all graphs.
    – CularBytes
    Apr 29, 2019 at 12:24
  • @CularBytes You do not sum up the values if you reset total to 0 in every footer method call. But I agree with you, it's not a good practice to store the values in the window. Apr 30, 2019 at 6:11
3

@Haider this is what you were looking for, I had the same problem. I have reused your code and built upon it @tektiv

I have made one small change where instead of building into the label I have made use of the afterbody. This removes the key color

afterBody code:

                afterBody: function (tooltipItem, data) {
                  var corporation = data.datasets[tooltipItem[0].datasetIndex].label;
                var valor = data.datasets[tooltipItem[0].datasetIndex].data[tooltipItem[0].index];
                var total = 0;
                for (var i = 0; i < data.datasets.length; i++)
                    total += data.datasets[i].data[tooltipItem[0].index];  
                return "Total : $" + total;
            }

Full code here at JSFiddle

Picture demonstration of the finished tooltip

2

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, " ");

                }
            }
        }
0

If you are on older ChartJs version you have to handle this in a different way. I'm using Chart.js Version 2.7.2 and this is how I handled it:

tooltips: {
            mode: 'label',
            callbacks: {
                footer: function (data) {
                    var total = 0;
                    for (var i = 0; i < data.length; i++) {
                        total += data[i].yLabel;
                    }
                    return 'Total: ' + total
                }
            }
        }
0

Chart.js made their own, very satisfying solution:

options: {
  interaction: {
    intersect: false,
    mode: 'index',
  },
  plugins: {
    tooltip: {
      callbacks: {
        footer: footer,
      }
    }
  }
}

and somewhere else in your code:

const footer = (tooltipItems) => {
  let sum = 0;

  tooltipItems.forEach(function(tooltipItem) {
    sum += tooltipItem.parsed.y;
  });
  return 'Sum: ' + sum;
};

Worked just fine for me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.