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

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

实现Chart.js堆叠折线图并自定义Y轴高度

Example Chart Image

我该如何创建如图所示的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属性控制轴的堆叠高度权重,同时修正基础配置错误:

  1. 修正x轴位置:你当前把x轴position设为left是错误的,需改为bottom才能正常显示横轴。
  2. 调整stackWeight权重:给需要加倍高度的y2轴设stackWeight: 2,其他Y轴设stackWeight: 1,这样y2轴的高度会自动是其他Y轴的2倍。
  3. 优化网格线显示:关闭轴内部网格线,避免视觉混乱。

修正后的完整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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 22:12:09