# 散点图与气泡图

URL: https://caijiao.org/chartjs/03-chart-types/06-scatter-bubble
Source: docs/chartjs/03-chart-types/06-scatter-bubble.md
Description: 介绍如何使用 Chart.js 创建散点图与气泡图，展示数据点的分布及大小关系，适用于多维数据的可视化分析。

散点图用于展示数据点在二维坐标系中的分布，气泡图则在散点基础上增加了气泡大小维度，适合展示三维数据。使用 [Chart.js](/chartjs/) 可以轻松绘制并自定义这两种图表，帮助分析变量间的关系。

## 散点图示例

```js
(function () {
  const ctx = document.getElementById("scatterChart").getContext("2d");
  const scatterChart = new Chart(ctx, {
    type: "scatter",
    data: {
      datasets: [
        {
          label: "样本数据",
          data: [
            { x: -10, y: 0 },
            { x: 0, y: 10 },
            { x: 10, y: 5 },
            { x: 0.5, y: 5.5 },
          ],
          backgroundColor: "rgba(255, 99, 132, 0.7)",
        },
      ],
    },
    options: {
      responsive: true,
      scales: {
        x: {
          type: "linear",
          position: "bottom",
          title: { display: true, text: "X 轴" },
        },
        y: {
          title: { display: true, text: "Y 轴" },
        },
      },
      plugins: {
        legend: { display: true },
        tooltip: { enabled: true },
      },
    },
  });
})();
```

[在线代码演示](/chartjs/demos/10-1.html)

## 气泡图示例

```js
(function () {
  const ctx = document.getElementById("bubbleChart").getContext("2d");
  const bubbleChart = new Chart(ctx, {
    type: "bubble",
    data: {
      datasets: [
        {
          label: "样本数据",
          data: [
            { x: 20, y: 30, r: 15 },
            { x: 40, y: 10, r: 10 },
            { x: 15, y: 25, r: 8 },
            { x: 25, y: 40, r: 12 },
          ],
          backgroundColor: "rgba(54, 162, 235, 0.7)",
        },
      ],
    },
    options: {
      responsive: true,
      scales: {
        x: {
          title: { display: true, text: "X 轴" },
        },
        y: {
          title: { display: true, text: "Y 轴" },
        },
      },
      plugins: {
        legend: { display: true },
        tooltip: { enabled: true },
      },
    },
  });
})();
```

[在线代码演示](/chartjs/demos/10-2.html)
