[Chartjs]-Getting chartsjs to show key of data label instead of value

4👍

You can use the formatter function for this:

Chart.register(ChartDataLabels)

const options = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: 'orange'
    }]
  },
  options: {
    plugins: {
      datalabels: {
        color: 'black',
        anchor: 'end',
        align: 'end',
        offset: 15,
        formatter: (val, ctx) => (ctx.chart.data.labels[ctx.dataIndex])
      },
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.js"></script>
</body>

Leave a comment