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

如何在Chart.js中让刻度标签在灰色背景内居中对齐?

Chart.js实现X轴标签在灰色背景区域内居中对齐

要让X轴的星期标签在灰色背景里居中对齐,你可以通过调整刻度(ticks)的内边距和坐标轴的内边距来实现,具体修改如下:

修改后的配置代码

scales: {
  x: {
    backgroundColor: '#f5f5f5',
    grid: {
      display: false,
    },
    // 控制灰色背景的上下空间,给标签居中预留区域
    padding: {
      top: 10,
      bottom: 10
    },
    ticks: {
      stepSize: 1,
      font: {
        weight: 700,
      },
      color: '#404040',
      // 调整标签与X轴线的距离,让标签向下偏移至背景居中位置
      padding: 8
    },
    offset: true,
  },
  y: {
    backgroundColor: '#f5f5f5',
    grid: {
      display: false,
    },
    ticks: {
      stepSize: 1,
      font: {
        weight: 700,
      },
      color: '#343b7e',
    },
    offset: true,
  },
},

关键修改说明

  • x.padding:设置坐标轴的上下内边距,扩展灰色背景的垂直高度,为标签居中提供足够空间。
  • x.ticks.padding:调整刻度标签与X轴线的间距,让标签向下偏移,刚好落在灰色背景的垂直居中位置。

你可以根据实际视觉效果,微调padding的数值(比如将top/bottom设为8、12,ticks的padding设为6、10),直到达到预期的居中效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 16:42:20