ChartJS x轴position属性设为center时标题不可见,如何解决?
问题现象
- 当x轴position未设置为center时,标题可以正常显示:

- 若将x轴的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
相关产品推荐
相关产品推荐

