关于 alterlab-matplotlib
为使用 Matplotlib 的研究者和开发者提供绘图指导,涵盖 pyplot 与面向对象接口,以及静态、动画和交互式可视化。还包括图表样式、导出和可运行的辅助脚本。
主要功能
- 01静态、动画与交互式绘图
- 02pyplot 与面向对象接口
- 03多面板图表布局
- 04样式、色图与标注定制
- 05导出 PNG、PDF、SVG
- 06绘图模板与样式配置脚本
适用场景
- 01绘制科学或统计图表
- 02制作含多个子图的图形
- 03调整图表样式并导出出版文件
- 04在 Jupyter 或 GUI 应用中使用绘图
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ alterlab-ieu/ alterlab-academic-skills --skill alterlab-matplotlib安装后在 Claude Code 中输入/alterlab-matplotlib确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
evals/evals.jsonreferences/api_reference.mdcommon_issues.mdplot_types.mdstyling_guide.mdscripts/plot_template.pystyle_configurator.py详细介绍
Matplotlib
概述
Matplotlib 是 Python 中用于创建静态、动画和交互式图表的基础可视化库。本技能介绍如何有效使用 matplotlib,涵盖 pyplot 接口(MATLAB 风格)和面向对象 API(Figure/Axes),并提供创建出版级可视化的最佳实践。
何时使用此技能
在以下情况下应使用此技能:
- 创建任何类型的绘图或图表(折线图、散点图、柱状图、直方图、热力图、等高线图等)
- 生成科学或统计可视化
- 自定义图表外观(颜色、样式、标签、图例)
- 使用子图创建多面板图表
- 将可视化内容导出为各种格式(PNG、PDF、SVG 等)
- 构建交互式图表或动画
- 处理 3D 可视化
- 将图表集成到 Jupyter Notebook 或 GUI 应用程序中
不适用场景
| 场景 | 改用 |
|---|---|
| 直接从 DataFrame 快速绘制统计图表(带自动置信区间的箱线图/小提琴图/配对图/回归图) | alterlab-seaborn |
| 带悬停/缩放功能的交互式图表、独立 HTML 或 Dash 仪表板 | alterlab-plotly |
| 可用于期刊发表的图表:栏宽、Okabe-Ito 调色板、面板标签、显著性星号 | alterlab-scientific-viz |
| 检查完成的图表是否存在标签重叠或裁切,并导出 300 dpi 图像 | alterlab-figure-qa |
| 绘制流程图、通路图或架构图,而不是数据图表 | alterlab-scientific-schematics |
核心概念
Matplotlib 的层级结构
Matplotlib 使用分层的对象结构:
- Figure - 包含所有图表元素的顶层容器
- Axes - 实际显示数据的绘图区域(一个 Figure 可以包含多个 Axes)
- Artist - 图表中所有可见的内容(线条、文本、刻度等)
- Axis - 负责处理刻度和标签的数轴对象(x 轴、y 轴)
两种接口
1. pyplot 接口(隐式,MATLAB 风格)
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()
- 适合快速绘制简单图表
- 自动维护状态
- 适用于交互式操作和简单脚本
2. 面向对象接口(显式)
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4])
ax.set_ylabel('some numbers')
plt.show()
- 适用于大多数场景,推荐使用
- 可以更明确地控制图表和坐标轴
- 更适合包含多个子图的复杂图表
- 更易于维护和调试
常见工作流
1. 创建基本图表
单图工作流:
import matplotlib.pyplot as plt
import numpy as np
# Create figure and axes (OO interface - RECOMMENDED)
fig, ax = plt.subplots(figsize=(10, 6))
# Generate and plot data
x = np.linspace(0, 2*np.pi, 100)
ax.plot(x, np.sin(x), label='sin(x)')
ax.plot(x, np.cos(x), label='cos(x)')
# Customize
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('Trigonometric Functions')
ax.legend()
ax.grid(True, alpha=0.3)
# Save and/or display
plt.savefig('plot.png', dpi=300, bbox_inches='tight')
plt.show()
2. 多个子图
创建子图布局:
# Method 1: Regular grid
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
axes[0, 0].plot(x, y1)
axes[0, 1].scatter(x, y2)
axes[1, 0].bar(categories, values)
axes[1, 1].hist(data, bins=30)
# Method 2: Mosaic layout (more flexible)
fig, axes = plt.subplot_mosaic([['left', 'right_top'],
['left', 'right_bottom']],
figsize=(10, 8))
axes['left'].plot(x, y)
axes['right_top'].scatter(x, y)
axes['right_bottom'].hist(data)
# Method 3: GridSpec (maximum control)
from matplotlib.gridspec import GridSpec
fig = plt.figure(figsize=(12, 8))
gs = GridSpec(3, 3, figure=fig)
ax1 = fig.add_subplot(gs[0, :]) # Top row, all columns
ax2 = fig.add_subplot(gs[1:, 0]) # Bottom two rows, first column
ax3 = fig.add_subplot(gs[1:, 1:]) # Bottom two rows, last two columns
3. 图表类型及适用场景
折线图 - 时间序列、连续数据、趋势
ax.plot(x, y, linewidth=2, linestyle='--', marker='o', color='blue')
散点图 - 变量之间的关系、相关性
ax.scatter(x, y, s=sizes, c=colors, alpha=0.6, cmap='viridis')
柱状图 - 类别比较
ax.bar(categories, values, color='steelblue', edgecolor='black')
# For horizontal bars:
ax.barh(categories, values)
直方图 - 分布
ax.hist(data, bins=30, edgecolor='black', alpha=0.7)
热力图 - 矩阵数据、相关性
im = ax.imshow(matrix, cmap='coolwarm', aspect='auto')
plt.colorbar(im, ax=ax)
等高线图 - 在二维平面上呈现 3D 数据
contour = ax.contour(X, Y, Z, levels=10)
ax.clabel(contour, inline=True, fontsize=8)
箱线图 - 统计分布
# 'tick_labels' replaced 'labels' in matplotlib 3.9 (old name removed in 3.11)
ax.boxplot([data1, data2, data3], tick_labels=['A', 'B', 'C'])
小提琴图 - 分布密度
ax.violinplot([data1, data2, data3], positions=[1, 2, 3])
如需全面了解图表类型示例及其变体,请参阅 references/plot_types.md。
4. 样式与自定义
颜色指定方式:
- 命名颜色:
'red'、'blue'、'steelblue' - 十六进制代码:
'#FF5733' - RGB 元组:
(0.1, 0.2, 0.3) - 色图:
cmap='viridis'、cmap='plasma'、cmap='coolwarm'
使用样式表:
plt.style.use('seaborn-v0_8-darkgrid') # Apply predefined style
# Available styles: 'ggplot', 'bmh', 'fivethirtyeight', etc.
print(plt.style.available) # List all available styles
使用 rcParams 自定义:
plt.rcParams['font.size'] = 12
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['axes.titlesize'] = 16
plt.rcParams['xtick.labelsize'] = 10
plt.rcParams['ytick.labelsize'] = 10
plt.rcParams['legend.fontsize'] = 12
plt.rcParams['figure.titlesize'] = 18
文本和注释:
ax.text(x, y, 'annotation', fontsize=12, ha='center')
ax.annotate('important point', xy=(x, y), xytext=(x+1, y+1),
arrowprops=dict(arrowstyle='->', color='red'))
如需了解详细的样式选项和色图指南,请参阅 references/styling_guide.md。
5. 保存图表
导出为各种格式:
# High-resolution PNG for presentations/papers
plt.savefig('figure.png', dpi=300, bbox_inches='tight', facecolor='white')
# Vector format for publications (scalable)
plt.savefig('figure.pdf', bbox_inches='tight')
plt.savefig('figure.svg', bbox_inches='tight')
# Transparent background
plt.savefig('figure.png', dpi=300, bbox_inches='tight', transparent=True)
重要参数:
dpi:分辨率(出版用途为 300,网页用途为 150,屏幕显示为 72)bbox_inches='tight':移除多余的空白facecolor='white':确保背景为白色(适用于透明主题)transparent=True:透明背景
6. 使用 3D 图表
# projection='3d' auto-registers the 3D axes; no Axes3D import needed
# (the old `from mpl_toolkits.mplot3d import Axes3D` is a no-op on modern matplotlib).
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
# Surface plot
ax.plot_surface(X, Y, Z, cmap='viridis')
# 3D scatter
ax.scatter(x, y, z, c=colors, marker='o')
# 3D line plot
ax.plot(x, y, z, linewidth=2)
# Labels
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
最佳实践
1. 接口选择
- 生产代码使用面向对象接口(fig, ax = plt.subplots())
- 仅在快速交互式探索时使用 pyplot 接口
- 始终显式创建图形,不要依赖隐式状态
2. 图形尺寸和 DPI
- 创建时设置 figsize:
fig, ax = plt.subplots(figsize=(10, 6)) - 根据输出媒介选择合适的 DPI:
- 屏幕/笔记本:72-100 dpi
- Web:150 dpi
- 印刷/出版物:300 dpi
3. 布局管理
- 使用
constrained_layout=True或tight_layout()防止元素重叠 - 推荐使用
fig, ax = plt.subplots(constrained_layout=True)自动调整间距
4. 颜色映射选择
- 顺序型(viridis、plasma、inferno):适用于呈现持续递进关系的有序数据
- 发散型(coolwarm、RdBu):适用于具有明确中心点(例如零值)的数据
- 定性型(tab10、Set3):适用于类别/名义数据
- 避免使用彩虹色映射(jet)——它们在感知上并不均匀
5. 无障碍性
- 使用对色盲友好的颜色映射(viridis、cividis)
- 柱状图除使用颜色外,还应添加图案/阴影线
- 确保各元素之间有足够的对比度
- 添加描述性标签和图例
6. 性能
- 对于大型数据集,在绘图调用中使用
rasterized=True以减小文件体积 - 绘图前进行适当的数据缩减(例如对密集时间序列降采样)
- 对于动画,使用 blitting 提高性能
7. 代码组织
# Good practice: Clear structure
def create_analysis_plot(data, title):
"""Create standardized analysis plot."""
fig, ax = plt.subplots(figsize=(10, 6), constrained_layout=True)
# Plot data
ax.plot(data['x'], data['y'], linewidth=2)
# Customize
ax.set_xlabel('X Axis Label', fontsize=12)
ax.set_ylabel('Y Axis Label', fontsize=12)
ax.set_title(title, fontsize=14, fontweight='bold')
ax.grid(True, alpha=0.3)
return fig, ax
# Use the function
fig, ax = create_analysis_plot(my_data, 'My Analysis')
plt.savefig('analysis.png', dpi=300, bbox_inches='tight')
快速参考脚本
此技能在 scripts/ 目录中提供了可运行的辅助脚本。直接运行这些脚本即可
生成图形或样式表,也可以将它们作为上述模式的示例来阅读。这些脚本需要
matplotlib>=3.9 和 numpy(直方图示例还需要 scipy)。
plot_template.py
运行 scripts/plot_template.py 可渲染任意受支持的图表类型(折线图、
散点图、柱状图、直方图、热力图、等高线图、箱线图、小提琴图、3d,或作为 GridSpec
拼图的 all)。每个 create_* 辅助函数都接受可选的 ax=,方便你组合自己的
多面板布局。
# Render the full montage at 300 DPI
python scripts/plot_template.py --plot-type all --output figure.png
# Single plot type
python scripts/plot_template.py --plot-type scatter --output scatter.png
style_configurator.py
运行 scripts/style_configurator.py 可预览样式预设(publication、
presentation、web、dark、minimal),并将其导出为可重复使用的 .mplstyle 文件。
python scripts/style_configurator.py --list # show presets
python scripts/style_configurator.py --preset publication \
--output my_style.mplstyle # export style sheet
python scripts/style_configurator.py --preset publication --preview
详细参考
如需全面了解,请参阅参考文档:
references/plot_types.md- 图表类型完整目录,含代码示例和使用场景references/styling_guide.md- 详细的样式选项、颜色映射和自定义说明references/api_reference.md- 核心类和方法参考references/common_issues.md- 常见问题排查指南
与其他工具集成
Matplotlib 可与以下工具良好集成:
- NumPy/Pandas - 直接根据数组和 DataFrame 绘图
- Seaborn - 构建于 matplotlib 之上的高级统计可视化工具
- Jupyter - 使用
%matplotlib inline或%matplotlib widget进行交互式绘图 - GUI 框架 - 在 Tkinter、Qt、wxPython 应用程序中嵌入
常见注意事项
- 元素重叠:使用
constrained_layout=True或tight_layout() - 状态混淆:使用面向对象接口,避免 pyplot 状态机带来的问题
- 图形过多导致内存问题:使用
plt.close(fig)显式关闭图形 - 字体警告:安装字体,或使用
plt.rcParams['font.sans-serif']屏蔽警告 - DPI 混淆:请记住,figsize 的单位是英寸,不是像素:
pixels = dpi * inches - 重复使用图形编号(3.11+):如果图形 1 已存在,
plt.subplots(num=1)或plt.subplot_mosaic(..., num=1)会引发ValueError——传入clear=True,或使用fig.subplots()/fig.subplot_mosaic()添加坐标轴。 - 在 3.11 中移除:
matplotlib.cm.get_cmap(改用matplotlib.colormaps[name])、plot_date(使用日期时间值调用plot),以及箱线图中的labels=(改用tick_labels=)。 - 在 3.11 中弃用(目前会发出警告;
vert将在 3.13 中移除):boxplot/violinplot中的vert=(改用orientation='horizontal',该选项自 3.10 起可用)、contourf输出中的clabel(叠加contour线并为其添加标签),以及原地修改Colormap.set_bad/set_under/set_over(改用cmap.with_extremes(bad=..., under=..., over=...))。