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

如何在Chart.js中为两个时间序列设置左右双Y轴(独立刻度)

如何在Chart.js中为两个时间序列设置左右独立Y轴刻度?

要实现两个时间序列分别对应左右Y轴(独立刻度),只需在Chart.js的配置中添加双Y轴的刻度定义,并为每个数据集指定对应的轴ID即可,具体修改如下:

修改后的完整代码

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>

<script>
var xValues = [8.8, 8.6, 9.0, 9.7, 9.5, 9.1, 9.0, 9.2, 9.0, 9.6];
var yValues = [31.0, 23.0, 23.0, 45.29, 44.21, 3.53, 83.0, 21.0, 80.0, 38.88]
var labels = ['W12', 'W13', 'W14', 'W15', 'W16', 'W17', 'W18', 'W1P', 'W2P', 'W3P'];

new Chart("id", {
  type: "line",
  data: {
    labels: labels,
    datasets: [{ 
      data: xValues,
      borderColor: "green",
      fill: false,
      label: "Salary",
      yAxisID: "y-axis-1" // 指定对应左侧Y轴
    }, { 
      data: yValues,
      borderColor: "orange",
      fill: false,
      label: "Ownership",
      yAxisID: "y-axis-2" // 指定对应右侧Y轴
    }]
  },
  options: {
    legend: {display: true},
    title: {
          display: true,
          text: "Salary & Ownership"
        },
    scales: {
      yAxes: [
        {
          id: "y-axis-1",
          position: "left", // 左侧Y轴
          ticks: {
            beginAtZero: false
          },
          scaleLabel: {
            display: true,
            labelString: "Salary" // 左侧轴标签
          }
        },
        {
          id: "y-axis-2",
          position: "right", // 右侧Y轴
          ticks: {
            beginAtZero: false
          },
          scaleLabel: {
            display: true,
            labelString: "Ownership" // 右侧轴标签
          },
          gridLines: {
            drawOnChartArea: false // 右侧轴网格线不覆盖图表区域,避免重叠
          }
        }
      ]
    }
  }
});
</script>

关键修改说明

  • 数据集关联轴:给每个dataset添加yAxisID属性,分别对应定义好的左右轴ID(y-axis-1和y-axis-2)
  • 双Y轴配置:在options.scales.yAxes数组中定义两个轴,通过position指定左右位置,同时可以自定义刻度、标签和网格线样式,避免视觉重叠
  • 轴标签优化:为每个Y轴添加scaleLabel,明确对应的数据系列,提升可读性

修改后,图表会呈现出你需要的效果:左侧Y轴对应Salary序列,右侧Y轴对应Ownership序列,两者使用独立的刻度范围。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 08:15:44