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

ChartJS x轴position属性设为center时标题不可见,如何解决?

问题现象
  • 当x轴position未设置为center时,标题可以正常显示:
    未居中的x轴
  • 若将x轴的position属性设置为center,标题就会消失:
    position设为center
复现用配置

原始使用的ChartJS配置如下:

const options = {
    maintainAspectRatio: false,
    scales: {
      x: {
        type: 'linear',
        min: 0,
        max: MAX_AGE,
        grid: {
          display: false,
        },
        title: {
          display: true,
          text: 'xaxis title',
        },
        position: 'center', // 如何让x轴居中时也能正常显示标题
      },
      y: {
        min: -10,
        max: 10,
        grid: {
          display: false,
        },
        title: {
          display: true,
          text: 'yaxis title',
        },
      },
    },
}
解决方法

出现该问题是因为x轴居中后,默认的标题绘制位置落在了画布可视区域外,只需给x轴标题增加padding、对齐配置调整偏移即可,修改后的配置如下:

const options = {
    maintainAspectRatio: false,
    scales: {
      x: {
        type: 'linear',
        min: 0,
        max: MAX_AGE,
        grid: {
          display: false,
        },
        title: {
          display: true,
          text: 'xaxis title',
          // 新增以下配置,数值可根据实际显示效果调整
          align: 'end',
          padding: {
            top: 30
          }
        },
        position: 'center',
      },
      y: {
        min: -10,
        max: 10,
        grid: {
          display: false,
        },
        title: {
          display: true,
          text: 'yaxis title',
        },
      },
    },
}

如果上述调整无法满足展示需求,也可以通过ChartJS自定义插件在指定位置单独绘制x轴标题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:39:02