Chartjs-Chart.js 3.x how to put a label on Line section

0๐Ÿ‘

โœ…

I suggest using external plugin like Chart Plugin DataLabels according to this comment. Setup steps for Chart.js 3.x:

  1. Import plugin and register:
Chart.register(ChartDataLabels);
  1. add Chart DataLabels customization inside chart options:
options: {
    ...
    plugins: {
        datalabels: {
            formatter: function(value, context) {
                return context.dataset.label;
            },
            color: function(context) {
                return context.dataset.color;
            }
        }
    }
}
let ctx=document.getElementById('ctx').getContext('2d');
Chart.register(ChartDataLabels);
var chart=new Chart(ctx, {
   type: 'bar',
   data: {
      labels: ['Status'],
      datasets: [{
         label: 'CATCHUP',
         data: [10],
         backgroundColor: '#FF9900',
         color: '#FFFFFF'
      }, {
         label: 'LIVE',
         data: [6],
         backgroundColor: '#B4F0A7',
         color: '#000000'
      }, {
         label: 'RECORDING',
         data: [20],
         backgroundColor: '#CC33CC',
         color: '#FFFFFF'
      }, {
         label: 'LIVE',
         data: [8],
         backgroundColor: '#B4F0A7',
         color: '#000000'
      }]
   },
   options: {
      responsive: false,
      legend: {
         position: 'right'
      },
      scales: {
         x: {
            stacked: true
         },
         y: {
            stacked: true
         }
      },
      indexAxis: 'y',
      plugins: {
        datalabels: {
          formatter: function(value, context) {
            return context.dataset.label;
          },
          color: function(context) {
            return context.dataset.color;
          }
        }
      }
   },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.2.0/chartjs-plugin-datalabels.min.js"></script>
<canvas id="ctx" width="700"></canvas>

Leave a comment