CharlesM
CharlesM

Reputation: 551

Show data values in Chart.js bars (version 3)

There is a thread with many answers on this topic (Show values on top of bars in chart.js), but it's all about version 2.x

Have you found any working solutions? How can data values be displayed on top of vertical barcharts (or next to horizontal barcharts)?

Upvotes: 2

Views: 9581

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31341

You can use the beta of the datalabels plugin.

Documentation: https://v2_0_0-rc_1--chartjs-plugin-datalabels.netlify.app/

Script tag: <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chartjs-plugin-datalabels.min.js"></script>

Install command: npm i chartjs-plugin-datalabels@next

Live example:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<canvas id="myChart" width="850" height="520"></canvas>
<script>
  var ctx = document.getElementById('myChart');
  
  Chart.register(ChartDataLabels); // first way of registering the plugin, registers them for all your charts
  
  var myChart = new Chart(ctx, {
    type: 'bar',
    plugins: [ChartDataLabels], // second way of registering plugin, register plugin for only this chart
    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: {
      responsive: false,
      plugins: {
        datalabels: {
          anchor: 'end', // remove this line to get label in middle of the bar
          align: 'end',
          formatter: (val) => (`${val}%`),
          labels: {
            value: {
              color: 'blue'
            }
          }

        }
      }
    }
  });
</script>

Upvotes: 6

Related Questions