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

Chart.js使用chartjs-plugin-datalabels时条形图数据标签无法居中问题

Chart.js使用chartjs-plugin-datalabels时条形图数据标签无法居中的解决方法

问题描述

我在Chart.js的条形图中使用chartjs-plugin-datalabels插件展示数值,但是数据标签始终无法居中显示。
我已经在datasets.datalabels配置项中覆盖了默认配置,将anchor、align参数均设置为center,也尝试过将标签位置设为右对齐,但发现数值越大,数据标签偏离居中位置的情况越严重。
异常效果截图:
bar chart
相关实现代码:

Chart.register(ChartDataLabels);

const data_tafkidim_cat_count = {
  labels: window.TafkidimCatCount.map((el) => el.TafkidCat.split(' ')).slice(0, pagination['tafkidim_cat_count'].show),
  datasets: [
    {
      data: window.TafkidimCatCount.map((el) => el.Total),
      backgroundColor: Setcolors(),
      borderColor: Setcolors(1),
      borderWidth: 1,
      datalabels: {
        anchor: 'center',
        align: 'center',
      },
    },
  ],
};
const config_tafkidim_cat_count = {
  type: 'bar',
  data: data_tafkidim_cat_count,
  options: {
    scales: {
      x: {
        grid: {
          borderColor: '#829AB1',
        },
        ticks: {
          color: '#627D98',
        },
        reverse: true,
      },
      y: {
        grid: {
          borderColor: '#829AB1',
        },
        beginAtZero: true,
        ticks: {
          color: '#627D98',
        },
      },
    },
    plugins: {
      title: {
        text: TL['tafkidim_cat_count'],
        padding: {
          bottom: 20,
        },
      },
      legend: {
        display: false,
      },
      tooltip: {
        callbacks: {
          title: (context) => {
            return context[0].label.replaceAll(',', ' ');
          },
        },
      },
    },
  },
};
const tafkidim_cat_count = new Chart('#tafkidim-cat-count'.Element().getContext('2d'), config_tafkidim_cat_count);

解决方案

你出现该问题的核心原因是横向条形图的配置和datalabels插件的坐标计算逻辑不匹配,按以下步骤调整即可:

  1. 首先确认条形图方向配置:Chart.js 3.x及以上版本已经废弃了horizontalBar类型,横向条形图需要显式添加indexAxis: 'y'配置,指定分类轴为y轴,否则条形绘制方向和坐标轴配置不匹配,会直接导致标签偏移。修改配置如下:
const config_tafkidim_cat_count = {
  type: 'bar',
  indexAxis: 'y', // 新增这行配置
  data: data_tafkidim_cat_count,
  options: {
    // 原有配置保持不变
  }
}
  1. 补全datalabels插件的全局配置,不要仅在dataset中配置,避免默认参数冲突。在options.plugins节点下新增如下配置:
datalabels: {
  anchor: 'center',
  align: 'center',
  offset: 0, // 清零默认偏移量,消除x轴翻转带来的计算偏差
  clamp: true, // 强制标签限制在条形区域内,不会超出边界
  textAlign: 'center'
}
  1. 如果你为x轴设置了自定义的min/max属性,请确保配置合理,不会压缩条形的实际绘制宽度。如果canvas容器是动态尺寸,在容器尺寸变化后调用tafkidim_cat_count.update()方法重新渲染图表,即可保证标签位置计算正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:45:03