mcpField
M
matplotlib

matplotlib

github.com/crazymsn数据与数据库2338 次安装22 周前更新
代码仓库

关于 matplotlib

matplotlib 技能为使用 Python Matplotlib 创建和定制图表提供指导,面向数据分析、科学可视化和出版图表制作。内容涵盖 pyplot 与面向对象接口、常见图表、样式、导出及实用脚本。

主要功能

  1. 01讲解 pyplot 与面向对象接口
  2. 02涵盖多种统计与科学图表
  3. 03定制颜色、标签和图例
  4. 04创建多面板与 3D 图表
  5. 05导出 PNG、PDF 和 SVG
  6. 06提供模板与样式配置脚本

适用场景

  1. 01绘制数据趋势、分布与变量关系
  2. 02制作用于论文的多面板图表
  3. 03调整图表样式并导出不同格式

安装

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

$npx skills add https://github.com/crazymsn/academic-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 应用程序中

核心概念

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
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)

等高线图 - 在二维平面上展示三维数据

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

箱线图 - 统计分布

ax.boxplot([data1, data2, data3], 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 图表
from mpl_toolkits.mplot3d import Axes3D

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
    • 网页: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/ 目录中包含辅助脚本:

plot_template.py

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

用法:

python scripts/plot_template.py
style_configurator.py

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

用法:

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. 状态混淆:使用面向对象接口,避免 pyplot 状态机问题
  3. 多个图形导致的内存问题:使用 plt.close(fig) 显式关闭图形
  4. 字体警告:安装字体,或使用 plt.rcParams['font.sans-serif'] 屏蔽警告
  5. DPI 混淆:请记住,figsize 的单位是英寸,而非像素:pixels = dpi * inches

其他资源

评论

支持 Markdown