Chartjs-Undefined labels piechart – chartjs

0👍

Labels array is not supposed to be in the dataset itself but is supposed to be in the main data object like so:

 var data = [{
   data: [50, 55, 60, 33],
   backgroundColor: [
     "#4b77a9",
     "#5f255f",
     "#d21243",
     "#B27200"
   ],
   borderColor: "#fff"
 }];

 var options = {
   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: {
      labels: ["India", "China", "US", "Canada"],
     datasets: data
   },
   options: options
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.4.0/dist/chartjs-plugin-datalabels.min.js"></script>
<canvas id="pie-chart"></canvas>

Leave a comment