如何修复 ChartJS 中超过限制的 y 轴值

How do I fix over limit y axis value in ChartJS

大家好!

我正在使用 chartjs-plugin-datalabels 通过在他的栏上方显示值来防止无法悬停的微小值,但是当其中之一具有最高值时,数据标签超出了图表容器的限制

更新:

此外,您可以使用 suggestedMax 选项,我认为这比提供填充要好

const options = {
  plugins: {
    datalabels: {
      color: '#374774',
      font: { family: 'MyriadSemiBold', size: 14 },
      align: 'end',
      anchor: 'end',
      formatter: (value) => {
        if (value > 0) {
          return localizeNumber(value)
        }

        return ''
      },
    },
    legend: { display: false },
  },
  scales: {
    x: {
      grid: { lineWidth: 0 },
      ticks: {
        display: false,
      },
    },
    y: {
      // Highest value in your datasets
      suggestedMax: highestValue > 0 ? highestValue + 1e5 : 10,
      grid: { color: '#DFDFDF' },
      ticks: {
        callback: (value) => {
          return abbreviateNumber(value)
        },
        font: { family: 'MyriadRegular', size: 14 },
        color: '#374774',
      },
    },
  },
}

最简单的解决方案是 add padding to the top of your chart (simple sample below). You may also play around with the datalabel plugin's clamping 选项在图表外时调整标签的位置。

const layoutOptions =  {
    padding: {
        top: 30  // Add 30 pixels of padding to top of chart.
    }
};

const data = {
    labels: ['Large', 'Small'],
    datasets: [{ data: [100, 2] }]
};

const config = {
    type: 'bar',
    data: data,
    options: {
        layout: layoutOptions,
        scales: { y: { beginAtZero: true, max: 100 } },
        plugins: {
            legend: { display: false },
            datalabels: { anchor: 'end', align: 'top' }
        }
    },
};

new Chart(document.getElementById('myChart'), config);
#myChart {
    max-height: 180px;
}
<div>
  <canvas id="myChart"></canvas>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>
<script>Chart.register(ChartDataLabels);</script>