ChartJS : chartjs-plugin-datalabels 值在错误的地方

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

我正在使用数据标签插件和 ChartJs 我希望该值位于图表的正上方 enter image description here

 plugins: {
        datalabels: {
          backgroundColor: function(context) {
            return context.dataset.backgroundColor;
          },
          anchor: 'end',
          align: 'top',
          clamp :true,
          display:'auto'
        }
        
      },

这是我的图表选项

您可以为 offset 参数使用可编写脚本的函数,唯一的缺点是它仅在开始时进行评估,而不是在动画完成后进行评估,因此您需要禁用动画,否则标签会推高了

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>