教程 chartjs tutorial

多 Y 轴

Chart.js 支持在同一图表中配置多个 Y 轴,方便展示不同量纲或范围的数据。每个数据集可以指定对应的 Y 轴,通过坐标轴的 id 关联。

以下示例展示了两个数据集绑定不同 Y 轴,实现左、右两侧显示不同刻度的效果。

js
(function () {
  const ctx = document.getElementById("multiYAxisChart").getContext("2d");

  new Chart(ctx, {
    type: "bar",
    data: {
      labels: ["一月", "二月", "三月", "四月"],
      datasets: [
        {
          label: "销售额 (千元)",
          data: [30, 50, 70, 60],
          backgroundColor: "rgba(75, 192, 192, 0.7)",
          yAxisID: "yLeft",
        },
        {
          label: "访问量 (千次)",
          data: [200, 300, 250, 400],
          backgroundColor: "rgba(255, 159, 64, 0.7)",
          yAxisID: "yRight",
        },
      ],
    },
    options: {
      responsive: true,
      scales: {
        yLeft: {
          type: "linear",
          position: "left",
          title: {
            display: true,
            text: "销售额 (千元)",
          },
        },
        yRight: {
          type: "linear",
          position: "right",
          title: {
            display: true,
            text: "访问量 (千次)",
          },
          grid: {
            drawOnChartArea: false,
          },
        },
      },
      plugins: {
        legend: { display: true },
      },
    },
  });
})();
在线代码演示
源码
<!DOCTYPE html>
<html lang="zh">

<head> <meta charset="UTF-8" /> <title>多 Y 轴示例</title> <script src="https://cdn.jsdelivr.net/npm/chart.js&quot;&gt;&lt;/script&gt; <style> body { max-width: 700px; margin: 2rem auto; font-family: sans-serif; background: #f9f9f9; padding: 1rem; text-align: center; }

canvas {
  background: #fff;
  border: 1px solid #ccc;
  margin: 1rem auto;
}

</style> </head>

<body> <canvas id="multiYAxisChart" width="700" height="400"></canvas> <script> (function () { const ctx = document.getElementById(‘multiYAxisChart’).getContext(‘2d’);

  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['一月', '二月', '三月', '四月'],
      datasets: [
        {
          label: '销售额 (千元)',
          data: [30, 50, 70, 60],
          backgroundColor: 'rgba(75, 192, 192, 0.7)',
          yAxisID: 'yLeft'
        },
        {
          label: '访问量 (千次)',
          data: [200, 300, 250, 400],
          backgroundColor: 'rgba(255, 159, 64, 0.7)',
          yAxisID: 'yRight'
        }
      ]
    },
    options: {
      responsive: true,
      scales: {
        yLeft: {
          type: 'linear',
          position: 'left',
          title: {
            display: true,
            text: '销售额 (千元)'
          }
        },
        yRight: {
          type: 'linear',
          position: 'right',
          title: {
            display: true,
            text: '访问量 (千次)'
          },
          grid: {
            drawOnChartArea: false
          }
        }
      },
      plugins: {
        legend: { display: true }
      }
    }
  });
})();

</script> </body>

</html>