ChartJS : chartjs-plugin-datalabels The value is in the wrong place

0👍

You can use a scriptable function for the offset parameter, only downside is that this is evaluated only at the beginning and not after the animations are done so you will need to disable animations because otherwise the labels get pushed up

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: 'pink'
    }]
  },
  options: {
    animation: false,
    plugins: {
      datalabels: {
        backgroundColor: function(context) {
          return context.dataset.backgroundColor;
        },
        anchor: 'end',
        align: 'top',
        clamp: true,
        display: 'auto',
        offset: (ctx) => {
          const {
            datasetIndex,
            dataIndex,
            chart
          } = ctx;
          const data = chart.getDatasetMeta(datasetIndex).data;

          return data[dataIndex].y - chart.chartArea.top - 22;
        }
      }
    }
  }
}

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.5.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