Skip to content

Matplotlib - 散点图

散点图 (Scatter Plot) 用于可视化两个数值变量之间的关系。数据集中的每个数据点都表示为二维平面上的一个标记(例如,点、圆、叉),其位置由其在水平 (x) 轴和垂直 (y) 轴上的值确定。

散点图非常适合识别以下模式:

  • 相关性 (Correlation): 正相关(y 随着 x 增加而增加的趋势)、负相关(y 随着 x 增加而减少的趋势)或无相关性。
  • 簇 (Clusters): 形成不同组的数据点。
  • 异常值 (Outliers): 远离主要数据群的点。
  • 趋势 (Trends): 变量之间的线性或非线性关系。

ax.scatter() 方法用于创建散点图。

ax.scatter(x, y, s=None, c=None, marker=None, cmap=None, alpha=None, **kwargs)
  • x, y: 数组类型 (Array-like)。数据点的水平和垂直坐标。
  • s: 标量 (Scalar) 或数组类型 (array-like)(默认值:rcParams['lines.markersize']**2)。标记的大小,单位是点平方。可用于编码第三个变量。
  • c: 颜色 (Color)、序列 (sequence) 或颜色序列。标记颜色。可以是:
    • 单一颜色格式字符串(例如,'red'、'#FF0000')。
    • 与 x 和 y 大小相同的颜色序列。
    • 通过 cmap 和 norm 映射到颜色的数值序列(编码第三个变量)。
  • marker: 字符串 (String)(默认值:'o')。标记样式(例如,'o'、.、,、'x'、'+'、's' 表示正方形、'd' 表示菱形)。
  • cmap: 字符串 (String) 或 Colormap 实例(默认值:rcParams['image.cmap'])。仅当 c 是浮点数数组时使用颜色映射表 (Colormap)。
  • alpha: 浮点数 (Float)(0.0 完全透明到 1.0 完全不透明)。标记的混合值,用于处理重叠的点。
  • linewidths: 标量 (Scalar) 或数组类型 (array-like)。标记边缘的宽度。
  • edgecolors: 颜色 (Color) 或颜色序列。标记边缘的颜色。
  • label: 字符串 (String)。点的标签,由 ax.legend() 使用。

示例:显示两个变量之间关系的散点图,并通过颜色或大小编码第三个变量。

import matplotlib.pyplot as plt
import numpy as np
# 生成样本数据
np.random.seed(42)
num_points = 100
x_coords = np.random.rand(num_points) * 10 # X 值介于 0 到 10 之间
y_coords = 2.5 * x_coords + np.random.randn(num_points) * 3 # Y 值具有线性趋势 + 噪声
# 生成用于颜色/大小编码的第三个变量 (可选)
point_sizes = np.random.rand(num_points) * 150 # 标记的大小
point_colors = np.random.rand(num_points) # 用于映射到颜色的值
# --- 创建散点图 ---
fig, ax = plt.subplots(figsize=(8, 6))
scatter_plot = ax.scatter(x_coords, y_coords,
s=point_sizes, # 基于 'point_sizes' 设置标记大小
c=point_colors, # 基于 'point_colors' 设置标记颜色
marker='o', # 使用圆形标记
cmap='viridis', # 用于 'point_colors' 的 Colormap
alpha=0.7, # 使标记略微透明
edgecolors='black', # 为标记添加黑色边缘
linewidths=0.5,
label='Data Points' # 图例的标签
)
# --- 自定义和标签 ---
ax.set_title('散点图示例 (大小和颜色编码)')
ax.set_xlabel('X 变量')
ax.set_ylabel('Y 变量')
ax.grid(True, linestyle='--', alpha=0.6)
# 添加颜色条 (colorbar) 以显示 'point_colors' 的映射
cbar = fig.colorbar(scatter_plot, label='颜色变量值')
# 添加图例 (如果使用了 'label' 并希望解释标记类型)
# 为大小图例创建代理艺术家 (更复杂)
handles, labels = scatter_plot.legend_elements(prop="sizes", alpha=0.6, num=4)
size_legend = ax.legend(handles, labels, loc="upper left", title="大小")
plt.show()

此示例创建一个散点图,其中每个点的位置由 x_coords 和 y_coords 确定。此外,每个标记的大小由 point_sizes 数组确定,颜色由 point_colors 数组确定,并使用 ‘viridis’ Colormap 进行映射。这允许在单个二维图上可视化最多四个维度的数据(x、y、大小、颜色)。添加了颜色条 (colorbar) 以解释颜色映射,并添加了一个基本图例 (legend) 以解释标记大小。