Get sum of total values in stacked Bar chart using ChartJs - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

Get sum of total values in stacked Bar chart using ChartJs

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){//www .  j a v  a  2 s . co m
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(82,154,190,0.5)",
        data: [50, 67, 78, 23, 40, 23, 55]
    }]
};
var ctx = document.getElementById("canvas").getContext("2d");
var 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 = 0;
                    for (var i = 0; i < data.datasets.length; i++)
                        total += data.datasets[i].data[tooltipItem.index];
                    if (tooltipItem.datasetIndex != data.datasets.length - 1) {
                        return corporation + " : $" + valor.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                    } else {
                        return [corporation + " : $" + valor.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,'), "Total : $" + total];
                    }
                }
            }
        },
        responsive: true,
        scales: {
            xAxes: [{
                stacked: true,
            }],
            yAxes: [{
                stacked: true
            }]
        }
    }
});
    }

      </script> 
   </head> 
   <body> 
      <canvas id="canvas" height="200"></canvas>  
   </body>
</html>

Related Tutorials