How to set percentage value by default on each bars in horizontal bar chart js

๐Ÿ‘:1

You can make use of the datalabels plugin

Example:

<script src="https://cdn.jsdelivr.net/npm/chart.js@3.3.0/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0-rc"></script>
<canvas id="myChart" width="850" height="520"></canvas>
<script>
  var ctx = document.getElementById('myChart');
  Chart.register(ChartDataLabels);
  Chart.defaults.set('plugins.datalabels', {
    color: '#FE777B'
  });
  var myChart = new Chart(ctx, {
    type: 'bar',
    plugins: [ChartDataLabels],
    data: {
      labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
      datasets: [{
        data: [12, 19, 3, 5, 2, 3],
        label: 'Advisor Closed MTD',
        backgroundColor: 'rgb(192,111,94)',
        barThickness: 25,
        datalabels: {
          color: '#FFCE56'
        }

      }],
    },
    options: {
      indexAxis: 'y',
      responsive: false,
      plugins: {
        datalabels: {
          formatter: (val, context) => (`${val}%`),
          anchor: 'end',
          align: 'end',
          labels: {
            value: {
              color: 'blue'
            }
          }

        }
      }
    }
  });
</script>

Leave a comment