ChartJS:chartjs-plugin-datalabels 未正确显示值

问题描述 投票:0回答:1

我正在尝试使用 Chart.js 创建图表,并且使用 4.4.1 版本来创建水平图表。

在我的代码中,数据标签当前显示为“x:222,y:1”,但我打算让它们仅显示主要值,即“222”。

我正在使用下面的脚本标签:

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js" ></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

下面是我的代码:

Chart.register(ChartDataLabels);
new Chart('myChart', {
  type: 'bar',
  plugins: [{
    afterInit: chart => {
      let dataset = chart.data.datasets[0];
      chart.data.datasets = chart.data.labels.map((l, i) => ({
        label: l,
        data: [{ x: dataset.data[i], y: i }],
        backgroundColor: dataset.backgroundColor[i],
        categoryPercentage: 1
      }));
      chart.data.labels = undefined;
    },
    beforeLayout: chart => {
      chart.options.scales.y1.labels = chart.data.datasets.filter((ds, i) => !chart.getDatasetMeta(i).hidden).map(ds => ds.label);
    }
  }],
  data: {     
    labels: ['Red', 'Blue', 'Green', 'Teal', 'Yellow', 'Purple', 'Orange', 'Black'],
    datasets: [{
      data: [123, 321, 213, 111, 222, 333, 234, 444],
      backgroundColor: ['Red', 'Blue', 'Green', 'Teal', 'Yellow', 'Purple', 'Orange', 'Black']
    }]
  },
  options: {
    indexAxis: 'y',
    maintainAspectRatio: false,
    plugins: {
        datalabels: {
        color: 'white',
      },
      legend: {
        position: 'top'
      },
      tooltip: {
        callbacks: {
          title: () => null
        }
      }
    },
      scales: {
          x: {
              title: {
                  display: true,
                  text: 'xAxis'
              }

          },
          y: {
                  display: false,
          },
          y1: {
              title: {
                  display: true,
                  text: 'yAxisLabel'
              },
              offset: true
          }
      }
  }, 
 
});

输出:

javascript canvas charts chart.js chart.js-datalabels
1个回答
1
投票

您可以使用

formatter
功能自定义数据标签的显示文本。

在您的情况下,您将显示

x
作为显示的数据标签。

datalabels: {
  ...,
  formatter: function (value, context) {
    return value.x;
},

演示@StackBlitz

© www.soinside.com 2019 - 2024. All rights reserved.