如何让Chart.js(v3)折线图起始于列中点而非左侧边缘?
问题:Chart.js折线图起始/结束位置调整到列中点
我正在使用Chart.js(v3)结合react-chartjs开发折线图,遇到了自定义折线位置的问题:折线总是从第一列的最左侧(Y轴0位置)开始,我希望折线能起始于第一列的中点,同时结束于最后一列的中点,而非列的边缘。
当前效果

期望效果

我的配置代码
<Line data={data} height={440} width={480} options={{ ...options, scales: { x: { grid: { color(context) { if (context.tick.value === 0) return '#B3B3B3'; return '#E6E6E6'; }, tickWidth: 0, lineWidth: 1, }, border: { dash(context) { if (context.tick.value === 0) return [0]; return [5, 5]; }, width: 0, }, ticks: { display: false, }, }, y: { grid: { color(context) { if ([0, 30, 70].includes(context.tick.value)) { return '#B3B3B3'; } return '#E6E6E6'; }, lineWidth(context) { if ([30, 70].includes(context.tick.value)) { return 2; } return 1; }, tickWidth: 0, }, border: { dash(context) { if (context.tick.value === 0) return [0]; return [5, 5]; }, width: 1, }, min: 0, max: 100, ticks: { font: { weight: 'bold', size: 10, family: 'Open Sans', }, color: '#000000', }, }, }, animation: false, plugins: { legend: { display: false, }, tooltip: { enabled: false, }, }, }} />
解决方案
只需在x轴配置中添加offset: true,并确保x轴类型为category(若未显式指定),即可让折线起始和结束于列的中点:
修改后的x轴配置
x: { type: 'category', // 显式指定分类轴,默认若data.labels为数组则自动识别 offset: true, // 关键配置:让刻度对齐列中点 grid: { color(context) { if (context.tick.value === 0) return '#B3B3B3'; return '#E6E6E6'; }, tickWidth: 0, lineWidth: 1, }, border: { dash(context) { if (context.tick.value === 0) return [0]; return [5, 5]; }, width: 0, }, ticks: { display: false, }, },
原理说明
offset: true会将x轴的刻度(以及对应的折线数据点)定位到每个分类列的中心位置,自然让折线的起点和终点落在第一列、最后一列的中点- 显式设置
type: 'category'可避免Chart.js自动推断轴类型时出现偏差,确保配置生效
内容的提问来源于stack exchange,提问作者PedroB
相关产品推荐
相关产品推荐

