教程 chartjs tutorial

混合图表

Chart.js 支持在同一张图表中混合不同类型的图形展示,例如柱状图结合折线图。这在展示多个数据维度时非常有用,比如比较销售总量与平均增长趋势。

创建混合图表的方式是将不同类型的数据集添加到 datasets 数组中,并分别设置 type 属性。下面的示例展示了柱状图与折线图的组合。

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

  new Chart(ctx, {
    data: {
      labels: ["一月", "二月", "三月", "四月", "五月"],
      datasets: [
        {
          type: "bar",
          label: "销售额",
          data: [50, 60, 70, 180, 190],
          backgroundColor: "rgba(75, 192, 192, 0.6)",
        },
        {
          type: "line",
          label: "增长率",
          data: [3, 4, 5, 10, 12],
          borderColor: "rgb(255, 99, 132)",
          backgroundColor: "rgba(255, 99, 132, 0.2)",
          fill: false,
          tension: 0.4,
          yAxisID: "y1",
        },
      ],
    },
    options: {
      responsive: true,
      plugins: {
        legend: { display: true },
      },
      scales: {
        y: {
          type: "linear",
          position: "left",
          title: { display: true, text: "销售额" },
        },
        y1: {
          type: "linear",
          position: "right",
          grid: { drawOnChartArea: false },
          title: { display: true, text: "增长率 (%)" },
        },
      },
    },
  });
})();
在线代码演示
源码
<!DOCTYPE html>
<html lang="zh">

<head> <meta charset="UTF-8"> <title>混合图表</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="mixedChart" width="700" height="400"></canvas> <script> (function () { const ctx = document.getElementById(‘mixedChart’).getContext(‘2d’);

  new Chart(ctx, {
    data: {
      labels: ['一月', '二月', '三月', '四月', '五月'],
      datasets: [
        {
          type: 'bar',
          label: '销售额',
          data: [50, 60, 70, 180, 190],
          backgroundColor: 'rgba(75, 192, 192, 0.6)'
        },
        {
          type: 'line',
          label: '增长率',
          data: [3, 4, 5, 10, 12],
          borderColor: 'rgb(255, 99, 132)',
          backgroundColor: 'rgba(255, 99, 132, 0.2)',
          fill: false,
          tension: 0.4,
          yAxisID: 'y1'
        }
      ]
    },
    options: {
      responsive: true,
      plugins: {
        legend: { display: true }
      },
      scales: {
        y: {
          type: 'linear',
          position: 'left',
          title: { display: true, text: '销售额' }
        },
        y1: {
          type: 'linear',
          position: 'right',
          grid: { drawOnChartArea: false },
          title: { display: true, text: '增长率 (%)' }
        }
      }
    }
  });
})();

</script> </body>

</html>