教程 chartjs tutorial

坐标轴设置

在使用 Chart.js 创建图表时,坐标轴的设置至关重要。你可以自定义坐标轴的类型、刻度显示、网格线样式和标签格式,从而让图表更清晰、易读,满足不同数据展示需求。

js
(function () {
  const ctx = document.getElementById("axisChart").getContext("2d");
  const axisChart = new Chart(ctx, {
    type: "line",
    data: {
      labels: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
      datasets: [
        {
          label: "销售额",
          data: [150, 200, 180, 220, 170, 210, 190],
          borderColor: "rgb(75, 192, 192)",
          fill: false,
          tension: 0.3,
        },
      ],
    },
    options: {
      responsive: true,
      scales: {
        x: {
          type: "category",
          ticks: {
            color: "#2c3e50",
            font: { size: 14, weight: "bold" },
          },
          grid: {
            display: false,
          },
          title: {
            display: true,
            text: "日期",
            color: "#34495e",
            font: { size: 16, weight: "bold" },
          },
        },
        y: {
          type: "linear",
          ticks: {
            color: "#2c3e50",
            font: { size: 14 },
          },
          grid: {
            color: "rgba(0,0,0,0.1)",
            borderDash: [5, 5],
          },
          title: {
            display: true,
            text: "销售额(元)",
            color: "#34495e",
            font: { size: 16, weight: "bold" },
          },
          beginAtZero: true,
        },
      },
      plugins: {
        legend: { display: true },
        tooltip: { enabled: true },
      },
    },
  });
})();
在线代码演示
源码
<!DOCTYPE html>
<html lang="zh">

<head> <meta charset="UTF-8" /> <title>Chart.js 坐标轴设置示例</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: Arial, sans-serif; background: #fafafa; padding: 1rem; }

canvas {
  background: #fff;
  border: 1px solid #ccc;
  display: block;
  margin: 0 auto;
}

</style> </head>

<body> <canvas id="axisChart" width="700" height="400"></canvas> <script> (function () { const ctx = document.getElementById(‘axisChart’).getContext(‘2d’); new Chart(ctx, { type: ‘line’, data: { labels: [‘周一’, ‘周二’, ‘周三’, ‘周四’, ‘周五’, ‘周六’, ‘周日’], datasets: [{ label: ‘销售额’, data: [150, 200, 180, 220, 170, 210, 190], borderColor: ‘rgb(75, 192, 192)’, fill: false, tension: 0.3 }] }, options: { responsive: true, scales: { x: { type: ‘category’, ticks: { color: ‘#2c3e50’, font: { size: 14, weight: ‘bold’ } }, grid: { display: false }, title: { display: true, text: ‘日期’, color: ‘#34495e’, font: { size: 16, weight: ‘bold’ } } }, y: { type: ‘linear’, ticks: { color: ‘#2c3e50’, font: { size: 14 } }, grid: { color: ‘rgba(0,0,0,0.1)’, borderDash: [5, 5] }, title: { display: true, text: ‘销售额(元)’, color: ‘#34495e’, font: { size: 16, weight: ‘bold’ } }, beginAtZero: true } }, plugins: { legend: { display: true }, tooltip: { enabled: true } } } }); })(); </script> </body>

</html>