mcpField
M
matplotlib

matplotlib

github.com/hkphysics数据与数据库043 次安装19 周前更新
代码仓库

关于 matplotlib

介绍如何使用 Matplotlib 创建和定制科学及统计图表,涵盖快速绘图、多面板图、动画和出版格式导出,并讲解 pyplot 与面向对象 API。

主要功能

  1. 01绘制折线图至热图等图表
  2. 02使用 pyplot 与面向对象 API
  3. 03创建多面板布局
  4. 04定制样式、标签和注释
  5. 05导出 PNG、PDF 和 SVG
  6. 06制作交互图表与动画

适用场景

  1. 01绘制科学数据
  2. 02比较类别与数据分布
  3. 03准备出版用图表
  4. 04制作 Notebook 可视化

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/hkphysics/scientific-agent-skills --skill matplotlib

安装后在 Claude Code 中输入/matplotlib确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
api_reference.md
common_issues.md
plot_types.md
styling_guide.md
scripts/
plot_template.py
style_configurator.py

详细介绍

Matplotlib

概述

Matplotlib 是 Python 的基础可视化库,用于创建静态、动画和交互式绘图。本技能介绍如何有效使用 matplotlib,涵盖 pyplot 接口(MATLAB 风格)和面向对象 API(Figure/Axes),以及创建适用于出版的高质量可视化图表的最佳实践。

适用场景

在以下情况下应使用本技能:

  • 创建任何类型的绘图或图表(折线图、散点图、柱状图、直方图、热力图、等高线图等)
  • 生成科学或统计可视化图表
  • 自定义绘图外观(颜色、样式、标签、图例)
  • 使用子图创建多面板图
  • 将可视化图表导出为各种格式(PNG、PDF、SVG 等)
  • 构建交互式绘图或动画
  • 处理 3D 可视化
  • 将绘图集成到 Jupyter 笔记本或 GUI 应用程序中

设置

对于项目开发,使用 uv 安装 Matplotlib:

uv add matplotlib

启用笔记本交互功能:

uv add matplotlib ipympl

然后在 Jupyter 中使用 %matplotlib widget 或 %matplotlib ipympl 启用 widget 后端。

Matplotlib 3.10 需要 Python 3.10+ 和 NumPy 1.23+。通过 Agg、PDF 和 SVG 等后端可以进行非交互式文件输出。对于 GUI 窗口,Matplotlib 会自动选择可用的后端;如果在由 uv 管理的 Python 中 TkAgg 无法运行,请使用 uv self update 和 uv python upgrade --reinstall 更新 uv 和 Python 构建版本,或使用 uv add pyside6 安装 Qt 后端。

核心概念

Matplotlib 层级结构

Matplotlib 使用分层的对象结构:

  1. Figure - 包含所有绘图元素的顶层容器
  2. Axes - 显示数据的实际绘图区域(一个 Figure 可以包含多个 Axes)
  3. Artist - 图中所有可见元素(线条、文本、刻度等)
  4. 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
fig.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)

等高线图 - 在 2D 平面上呈现 3D 数据

contour = ax.contour(X, Y, Z, levels=10)
ax.clabel(contour, inline=True, fontsize=8)

箱线图 - 统计分布

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
fig.savefig('figure.png', dpi=300, bbox_inches='tight', facecolor='white')

# Vector format for publications (scalable)
fig.savefig('figure.pdf', bbox_inches='tight')
fig.savefig('figure.svg', bbox_inches='tight')

# Transparent background
fig.savefig('figure.png', dpi=300, bbox_inches='tight', transparent=True)

重要参数:

  • dpi:分辨率(出版物用 300,网页用 150,屏幕用 72)
  • bbox_inches='tight':移除多余的空白
  • facecolor='white':确保背景为白色(适用于透明主题)
  • transparent=True:透明背景
6. 使用 3D 绘图
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')
fig.savefig('analysis.png', dpi=300, bbox_inches='tight')

快速参考脚本

此技能在 scripts/ 目录中包含辅助脚本:

plot_template.py

演示多种绘图类型和最佳实践的模板脚本。可将其用作创建新可视化的起点。

用法:

uv run python scripts/plot_template.py
style_configurator.py

用于配置 matplotlib 样式偏好并生成自定义样式表的交互式实用工具。

用法:

uv run python scripts/style_configurator.py

详细参考资料

如需全面信息,请查阅参考文档:

  • 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 应用程序

常见注意事项

  1. 元素重叠:使用 constrained_layout=True 或 tight_layout()
  2. 状态混淆:使用 OO 接口,避免 pyplot 状态机问题
  3. 多个图形导致内存问题:使用 plt.close(fig) 显式关闭图形
  4. 字体警告:安装字体,或使用 plt.rcParams['font.sans-serif'] 禁用警告
  5. DPI 混淆:请记住,figsize 的单位是英寸,而非像素:pixels = dpi * inches

其他资源

评论

支持 Markdown