Chartjs-How to show lables just outside the the doughnut chart in Chartjs?

0👍

You can use chartjs-plugin-piechart-outlabels plugin to display the datalabels outside. You need to use the newer 2.8.0 version of the chartjs and also use the chartjs-plugin-datalabels and chartjs-plugin-piechart-outlabels plugins cdn’s to make it work.

  <div class="container panel-body">
    <canvas id="myChart"></canvas>
  </div>
  
  <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0/dist/chartjs-plugin-datalabels.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-piechart-outlabels"></script>

You can style the outlabels in the chart options => plugins => outlabels

let myChart = document.getElementById("myChart").getContext("2d");

      let massPopChart = new Chart(myChart, {
        type: "doughnut", // bar, horizontalBar, pie, line, doughnut, radar, polarArea
        data: {
          labels: [
           "Students",
           "Instructor",
           "Admins"
         ],
          datasets: [
            {
              data: [60, 30, 10],
              backgroundColor:['#1F78B4','#A6CEE3','#B2DF8A'],
              borderWidth: 0,
            },
          ],
        },
        options: {
          legend: {
                        display: false,
                    },
          layout: {
            padding: {
              left: 200,
              right: 200,
              bottom: 300,
              top: 0,
            },
          },
          cutoutPercentage: 85,
          plugins: {
          legend: false,
            datalabels:{
                display:false
            },
            outlabels: {
               text: '%l %p',
               color: 'white',
               stretch: 20,
               font: {
                   resizable: true,
                   minSize: 12,
                   maxSize: 18
               }
            }
          }          
        },

      });
    
      Chart.pluginService.register({
  beforeDraw: function(chart) {
    var width = chart.chart.width,
        height = chart.chart.height,
        ctx = chart.chart.ctx;

    ctx.restore();
    var fontSize = 3;
    ctx.font = fontSize + "em sans-serif";
    ctx.textBaseline = "middle";

    var text = "75%",
        textX = 245,
        textY = 140;
    ctx.fillText(text, textX, textY);
    ctx.save();
  }
});

Leave a comment