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

如何在Chart.js中居中水平堆叠条形图的标签?

解决Chart.js水平堆叠条形图数据标签垂直居中问题

问题分析

你的配置存在两个核心问题:

  • 配置结构错误:beginAtZero和stacked属性被错误写在scales对象外部,导致堆叠和坐标轴起始值配置不生效,间接干扰标签定位逻辑。
  • 标签定位逻辑偏差:水平条形图(indexAxis: "y")的垂直居中需要结合正确的anchor与align组合,默认配置可能因布局异常失效。

解决方案

1. 修正配置结构

将x、y轴的beginAtZero、stacked属性移至scales内部对应轴的配置中,同时移除无效的cutout属性(该属性仅适用于环形图):

{
    indexAxis: "y",
    animation: false,
    aspectRatio: 0.2,
    maintainAspectRatio: false,
    // 添加布局padding避免标签被遮挡
    layout: {
        padding: {
            top: 15,
            bottom: 5
        }
    },
    scales: {
        x: {
            beginAtZero: true,
            stacked: true
        },
        y: {
            beginAtZero: true,
            stacked: true
        }
    },
    plugins: {
        title: {
            color: "gray",
            font: {
                weight: "bold",
                size: 12
            }
        },
        legend: {
            display: false,
            position: "top"
        },
        datalabels: {
            color: "white",
            anchor: "center", // 控制垂直方向定位
            align: "center", // 控制水平方向定位
            textAlign: "center",
            // 强制绑定条形中心点坐标,确保垂直居中
            position: (ctx) => {
                const bar = ctx.chart.getDatasetMeta(ctx.datasetIndex).data[ctx.dataIndex];
                return { x: bar.x, y: bar.y };
            },
            formatter: (val: number, ctx: Context): string => {
              if (val) {
                const label = ctx.chart.data.labels[ctx.datasetIndex] as string;
                const value = ctx.chart.data.datasets[ctx.datasetIndex].data[0];
                return `${label} (${value})`;
              }
              return '';
            },
        },
        tooltip: {
            enabled: true,
            callbacks: {
              title: (): string => '',
              label: (tooltipItem: any): string => {
                const { chart } = tooltipItem;
                const label = chart.data.labels[tooltipItem.datasetIndex];
                const value: number = chart.data.datasets[tooltipItem.datasetIndex].data[0];
                return `${label}: ${value}`;
              },
            },
        },
    },
}

2. 关键配置说明

  • 水平条形图中,anchor: "center"负责垂直方向居中,align: "center"负责水平方向居中,修正轴配置后该组合即可正常生效。
  • 自定义position函数是兜底方案:直接获取条形的中心点坐标,强制标签绑定该位置,避免布局异常导致的偏移。
  • layout.padding.top可根据标签实际高度调整,彻底解决小尺寸图表下标签被顶部遮挡的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 07:53:27