You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chart.js水平条形图实现Y轴标签显示在每个条形顶部的方案咨询

解决步骤

  1. 首先确认版本适配:Chart.js 2.9.4需搭配chartjs-plugin-datalabels@1.x版本使用,2.0及以上版本的datalabels插件仅兼容Chart.js 3.x,版本不匹配会导致插件完全不生效。
  2. 隐藏原有Y轴分类标签:原有Y轴的默认刻度标签会显示在图表左侧,需要先关闭避免重复显示。
  3. 调整datalabels配置:针对水平条形图的坐标轴特性修改锚点、对齐方式,同时将formatter改为返回对应Y轴的分类文本而非数值。

调整后的完整配置代码

createAreaChart() {
  this.barChart1 = document.getElementById('barChart1');
  this.ctx1 = this.barChart1.getContext('2d');

  let i = 0;
  this.data1.forEach(div => {
    if(i==0){
      this.backgroundColors.push('#A60A2D');
    } if(i==1) {
      this.backgroundColors.push('#00A2C3');
    } if(i==2) {
      this.backgroundColors.push('#434F55');
      i = -1;
    }
    i++;
  });
  // 提前存储labels数组方便datalabels调用
  const chartLabels = this.data1.map(r => r.icon);
  this.chart1 = new Chart(this.ctx1, {
    type: 'horizontalBar',
    data: {
      labels: chartLabels,
      datasets: [{
        data: this.data1.map(r => r.total),
        label: 'Annual Cost',
        backgroundColor: this.backgroundColors,
        borderColor: this.backgroundColors,
        borderWidth: 1
      }]
    },
    options: {
      legend: {
        display: false
      },
      // 配置datalabels插件
      plugins: {
        datalabels: {
          // 锚点设置为条形的上边缘
          anchor: 'start',
          // 对齐到锚点的上方
          align: 'top',
          // 偏移量调整,避免和条形重叠
          offset: 4,
          // formatter返回对应位置的Y轴文本
          formatter: (value, context) => {
            return chartLabels[context.dataIndex];
          },
          font: {
            weight: 'bold'
          }
        }
      },
      layout: {
        padding: {
          // 顶部增加预留空间放标签,避免标签被截断
          top: 20,
          left: 0,
          right: 0,
          bottom: 0
        }
      },
      tooltips: {
        callbacks: {
          label: function(tooltipItem, data) {
            var value = data.datasets[0].data[tooltipItem.index];
            if (parseInt(value) >= 1000) {
              return '$' + value.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            } else {
              return '$' + value.toFixed(2).toString();
            }
          }
        }
      },
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true,
            precision: 2,
            // 隐藏原有Y轴的分类标签
            display: false,
            userCallback : function(value, index, values) {
              if(parseInt(value) >= 1000){
                return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
              } else {
                return '$' + value;
              }
            }
          }
        }]
      }
    }
  });
  this.chart1.height = 225;
}

补充说明

如果需要同时显示数值和Y轴文本,可以在formatter里拼接返回值,按需调整offset和padding参数即可适配不同的文本长度。

内容的提问来源于stack exchange,提问作者Jesus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 16:36:05