Chartjs-Laravel โ€“ How to Display both count and percentage (%) in chartjs pie chart

0๐Ÿ‘

โœ…

You can do this by defining a tooltip label callback function as follows.

tooltips: {
  callbacks: {
    label: (tooltipItem, data) => {
      var value = data.datasets[0].data[tooltipItem.index];
      var total = data.datasets[0].data.reduce((a, b) => a + b, 0);
      var pct = 100 / total * value;
      var pctRounded = Math.round(pct * 10) / 10;
      return value + ' (' + pctRounded + '%)';
    }
  }
}

Please have a look at below runnable code snippet.

new Chart('empGender', {
  type: 'doughnut',
  data: {
    labels: ['Male', 'Female'],
    datasets: [{
      backgroundColor: ['#f56954', '#00a65a'],
      borderColor: ['rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)'],
      data: [17, 7],
      borderWidth: 1
    }]
  },
  options: {
    maintainAspectRatio: true,
    responsive: true,
    cutoutPercentage: 80,
    tooltips: {
      callbacks: {
        label: (tooltipItem, data) => {
          var value = data.datasets[0].data[tooltipItem.index];
          var total = data.datasets[0].data.reduce((a, b) => a + b, 0);
          var pct = 100 / total * value;
          var pctRounded = Math.round(pct * 10) / 10;
          return value + ' (' + pctRounded + '%)';
        }
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="empGender" height="100"></canvas>

Leave a comment