Skip to content

Matplotlib - 箱线图

箱线图(box plot,或称为箱形图,box-and-whisker plot)提供了一个数据集分布的简洁视觉摘要。它显示了关键的统计度量:

  • 中位数 (Median): 箱体内的中心线(第 50 百分位数)。
  • 四分位距 (IQR): 箱体本身代表第一四分位数(Q1,第 25 百分位数)和第三四分位数(Q3,第 75 百分位数)之间的范围。箱体的长度表示中间 50% 数据的离散程度。
  • 须 (Whiskers): 从箱体延伸出的线条,通常延伸到距离箱体边缘 1.5 倍 IQR 的位置,或到此范围内的最小/最大数据点。
  • 离群值 (Outliers): 绘制在须以外的单个点,代表潜在的极端值。

箱线图对于并排比较不同数据集的分布特别有用。

我们将使用 NumPy 的随机数生成器来创建样本数据,模拟来自不同组的测量值。

import numpy as np
# Use the recommended modern way to generate random numbers
# 使用推荐的现代方式生成随机数
rng = np.random.default_rng(seed=42) # Seed for reproducibility
# seed=42 用于保证可复现性
# Create four datasets with different distributions
# 创建四个具有不同分布的数据集
data_group1 = rng.normal(loc=100, scale=10, size=200) # Mean 100, Std Dev 10
# 均值 100,标准差 10
data_group2 = rng.normal(loc=80, scale=30, size=200) # Mean 80, Std Dev 30
# 均值 80,标准差 30
data_group3 = rng.normal(loc=90, scale=20, size=200) # Mean 90, Std Dev 20
# 均值 90,标准差 20
data_group4 = rng.normal(loc=70, scale=25, size=200) # Mean 70, Std Dev 25
# 均值 70,标准差 25
# Combine the datasets into a list for plotting
# 将数据集组合到一个列表中用于绘图
data_to_plot = [data_group1, data_group2, data_group3, data_group4]

使用 ax.boxplot() 方法(利用面向对象 API)来创建图表。主要输入是数据集列表或一个二维数组,其中列代表数据集。

import matplotlib.pyplot as plt
import numpy as np
# (Include data generation code from above)
# (包含上面数据生成代码)
rng = np.random.default_rng(seed=42)
data_group1 = rng.normal(loc=100, scale=10, size=200)
data_group2 = rng.normal(loc=80, scale=30, size=200)
data_group3 = rng.normal(loc=90, scale=20, size=200)
data_group4 = rng.normal(loc=70, scale=25, size=200)
data_to_plot = [data_group1, data_group2, data_group3, data_group4]
# --- Create Plot ---
# --- 创建图表 ---
fig, ax = plt.subplots(figsize=(8, 6))
# Create the boxplot
# 创建箱线图
# 'patch_artist=True' fills the boxes with color
# 'patch_artist=True' 会用颜色填充箱体
# 'showmeans=True' displays the mean as a marker
# 'showmeans=True' 会将均值显示为一个标记
bp = ax.boxplot(data_to_plot, patch_artist=True, showmeans=True,
boxprops=dict(facecolor='lightblue'),
medianprops=dict(color='red', linewidth=2),
meanprops=dict(marker='D', markeredgecolor='black', markerfacecolor='green'))
# --- Customize Plot ---
# --- 自定义图表 ---
ax.set_title('Comparison of Data Distributions')
ax.set_ylabel('Measurement Value')
ax.set_xlabel('Data Group')
# Set custom labels for the x-axis ticks
# 为 x 轴刻度设置自定义标签
ax.set_xticklabels(['Group 1', 'Group 2', 'Group 3', 'Group 4'])
ax.yaxis.grid(True, linestyle='--', which='major', color='grey', alpha=0.5)
plt.show()

此代码将生成一个包含四个箱线图的图,每个数据组一个。箱体将是浅蓝色,中位数是红色,均值用绿色菱形标记。为 x 轴提供了自定义标签,并且水平网格有助于比较。此可视化清晰地显示了各组之间中位数、离散程度 (IQR) 和离群值存在的差异。

  • x: 输入数据(数组列表或二维数组)。
  • vert: 设置为 False 以绘制水平箱线图。
  • patch_artist: 如果为 True,则使用 Patch 艺术家绘制箱体,允许填充颜色。
  • labels: 一个字符串列表,用于标记 x 轴上的每个箱线图。
  • showmeans: 如果为 True,则显示算术均值。
  • showfliers: 如果为 False,则隐藏离群点。
  • meanprops、medianprops、boxprops、whiskerprops、capprops、flierprops: 字典,用于定制不同图表元素的外观。