ChartJS: Show all tooltips with Total for Multi Pie chart - Javascript Chart.js

Javascript examples for Chart.js:Pie Chart

Description

ChartJS: Show all tooltips with Total for Multi Pie chart

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.7.2/Chart.min.js"></script> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*from w  w  w  .  j  a  va  2s . com*/
var data = {
  datasets: [
    {
      data: [30, 32, 38, 50],
      labels: ["Mumbai", "Chennai", "Hyderabad", "Bangalore"],
      backgroundColor: [
        "#4b77a9",
        "#5f255f",
        "#d21243",
        "#B27200"
      ],
      borderColor: "#fff"
    }, {
      data: [80, 70],
      labels: ["Arrivals", "Departure"],
      backgroundColor: [
        "#92d400",
        "#bbb"
      ],
      borderColor: "#fff"
    }
  ]
};
var options = {
  cutoutPercentage: 15,
  tooltips: {
     custom: function(tooltip) {
    tooltip.displayColors = false;
    },
    callbacks: {
      label: function (tooltipItem, data) {
        var labels = data.datasets[tooltipItem.datasetIndex].labels;
        var values = data.datasets[tooltipItem.datasetIndex].data;
        var value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
        var colour = data.datasets[tooltipItem.datasetIndex].backgroundColor
        var total = 0;
        for (var i in values) {
          total += values[i];
       }
        var totally = total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        var label = [];
        for (var j in labels) {
           var percentage = Math.round((values[j] / total) * 100);
          label.push (labels[j] + " : " + values[j].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + ' (' + percentage + '%)');
        }
        label.push("Total : " + totally)
        return label;
      }
    }
  }
};
var ctx = document.getElementById("pieChart").getContext('2d');
var myChart = new Chart(ctx, {
  type: 'doughnut',
  data: data,
  options: options
});
    }

      </script> 
   </head> 
   <body> 
      <canvas id="pieChart"></canvas> 
      <div id="legend"></div>  
   </body>
</html>

Related Tutorials