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

如何在LWC的ChartJS水平堆叠单条形图下方显示数据集标签

实现水平堆叠条形图下方显示数据集标签(ChartJS v2.8.0 + LWC)

针对你的需求,要在水平堆叠单条形图的每个条形下方显示对应的数据集标签(Completed、In Progress、Waiting),可以通过调整chartjs-plugin-datalabels的配置来实现,同时修正原有代码中的几个小问题:

关键修改点

  1. 修正ChartJS v2配置错误:

    • 移除indexAxis: 'x':ChartJS v2中horizontalBar类型默认就是水平方向,该配置是v3版本新增的,v2不支持
    • 修正拼写错误:resposive改为responsive
  2. 配置datalabels插件显示数据集标签:

    • 通过formatter回调指定显示数据集的label而非默认数值
    • 设置position: 'bottom'让标签显示在条形下方,align: 'center'保证标签与条形居中对齐
    • 调整offset控制标签与条形的间距,通过font配置优化标签样式

修改后的完整代码

Chart.plugins.register(ChartDataLabels);
new Chart(
  document.getElementById('myChart'),
  {
    type: 'horizontalBar',
    data: {
      labels: ["#count"],
      datasets: [
        {
          label: 'Completed',
          barPercentage: 0.5,
          barThickness: 6,
          maxBarThickness: 8,
          minBarLength: 2,
          backgroundColor: "blue",
          data: [10],
        },
        {
          label: 'In Progress',
          barPercentage: 0.5,
          barThickness: 6,
          maxBarThickness: 8,
          minBarLength: 2,
          backgroundColor: "orange", // 建议区分颜色便于识别
          data: [65],
        },
        {
          label: 'Waiting',
          barPercentage: 0.5,
          barThickness: 6,
          maxBarThickness: 8,
          minBarLength: 2,
          backgroundColor: "gray", // 建议区分颜色便于识别
          data: [80],
        },
      ]
    },
    options: {
      responsive: true,
      scales: {
        xAxes: [{
          stacked: true
        }],
        yAxes: [{
          stacked: true
        }]
      },
      plugins: {
        datalabels: {
          clamp: true,
          color: "black",
          position: 'bottom', // 标签位置:条形下方
          align: 'center', // 标签与条形居中对齐
          offset: 10, // 标签与条形的间距
          formatter: function(value, context) {
            // 返回当前数据集的label
            return context.dataset.label;
          },
          font: {
            weight: "bold",
            size: 12
          }
        }
      }
    }
  });

额外建议

  • 给不同数据集设置不同的backgroundColor,能更直观地区分每个条形对应的状态
  • 如果标签显示位置仍需微调,可以调整offset数值或修改align为'left'/'right'适配需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:00:56