Chart.js多Y轴共享X轴堆叠折线图:如何设置y2轴高度为其他轴2倍
实现Chart.js堆叠折线图并自定义Y轴高度

我该如何创建如图所示的Chart.js堆叠折线图?但我希望y2轴的高度是其他Y轴的2倍。我已经能够创建多Y轴,但无法设置任意轴的高度。
用户当前的scales配置代码:
let scales = { x: { type: "linear", position: "left", max: res.maxs[0], }, y: { type: "linear", position: "left", stack: "demo", stackWeight: 2, grid: { borderColor: colors.blue, }, max: res.maxs[4], min: 0, title: { display: true, text: titlesLabelY[3], font: { size: 11, }, }, }, y2: { type: "linear", position: "left", stack: "demo", stackWeight: 2, grid: { borderColor: colors.blue, }, max: res.maxs[3], min: 0, title: { display: true, text: titlesLabelY[2], font: { size: 11, }, }, ticks: { callback: (value, index, values) => (index == (0)) ? undefined : value.toFixed(1), }, }, };
解决方案
要实现指定Y轴高度占比的需求,核心是利用Chart.js的stackWeight属性控制轴的堆叠高度权重,同时修正基础配置错误:
- 修正x轴位置:你当前把x轴
position设为left是错误的,需改为bottom才能正常显示横轴。 - 调整stackWeight权重:给需要加倍高度的y2轴设
stackWeight: 2,其他Y轴设stackWeight: 1,这样y2轴的高度会自动是其他Y轴的2倍。 - 优化网格线显示:关闭轴内部网格线,避免视觉混乱。
修正后的完整scales配置:
let scales = { x: { type: "linear", position: "bottom", // 修正x轴位置为底部 max: res.maxs[0], grid: { display: false // 可选:关闭x轴网格线,提升清晰度 } }, y: { type: "linear", position: "left", stack: "demo", stackWeight: 1, // 基准高度权重 grid: { borderColor: colors.blue, drawOnChartArea: false // 仅显示轴边框,不绘制内部网格 }, max: res.maxs[4], min: 0, title: { display: true, text: titlesLabelY[3], font: { size: 11, }, }, }, y2: { type: "linear", position: "left", stack: "demo", stackWeight: 2, // 权重设为2,高度为y轴的2倍 grid: { borderColor: colors.blue, drawOnChartArea: false }, max: res.maxs[3], min: 0, title: { display: true, text: titlesLabelY[2], font: { size: 11, }, }, ticks: { callback: (value, index, values) => (index === 0) ? undefined : value.toFixed(1), }, }, };
额外注意事项:
- 确保每个数据集通过
yAxisID绑定到对应轴(比如在dataset配置中添加yAxisID: 'y'或yAxisID: 'y2') - 若添加更多Y轴,只需将其加入同一个
stack组,并设置对应的stackWeight即可按比例分配高度
内容的提问来源于stack exchange,提问作者Holeng
相关产品推荐
相关产品推荐

