ChartJS datalabels to show percentage value in Pie piece - Javascript Chart.js

Javascript examples for Chart.js:Pie Chart

Description

ChartJS datalabels to show percentage value in Pie piece

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>Show percentage in Pie Piece </title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 
      <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://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.4.0/dist/chartjs-plugin-datalabels.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){//from  w w  w. ja v a  2  s  .  co m
 var data = [{
            data: [50, 55, 60, 33],
            labels: ["India", "China", "US", "Canada"],
            backgroundColor: [
                "#4b77a9",
                "#5f255f",
                "#d21243",
                "#B27200"
            ],
            borderColor: "#fff"
        }];
           var options = {
           tooltips: {
         enabled: false
    },
             plugins: {
            datalabels: {
                formatter: (value, ctx) => {
                  let sum = 0;
                  let dataArr = ctx.chart.data.datasets[0].data;
                  dataArr.map(data => {
                      sum += data;
                  });
                  let percentage = (value*100 / sum).toFixed(2)+"%";
                  return percentage;
                },
                color: '#fff',
                     }
        }
    };
        var ctx = document.getElementById("pie-chart").getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'pie',
        data: {
            datasets: data
        },
              options: options
    });
    }

      </script> 
   </head> 
   <body> 
      <canvas id="pie-chart"></canvas>  
   </body>
</html>

Related Tutorials