matplotlib by davila7/claude-code-templates
npx skills add https://github.com/davila7/claude-code-templates --skill matplotlibMatplotlib 是 Python 的基础可视化库,用于创建静态、动画和交互式图表。本技能提供了有效使用 matplotlib 的指导,涵盖了 pyplot 接口(MATLAB 风格)和面向对象的 API(Figure/Axes),以及创建出版物质量可视化的最佳实践。
在以下情况下应使用此技能:
Matplotlib 使用对象的层次结构:
1. pyplot 接口(隐式,MATLAB 风格)
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4])
ax.set_ylabel('some numbers')
plt.show()
单图工作流程:
import matplotlib.pyplot as plt
import numpy as np
# 创建图形和坐标轴(OO 接口 - 推荐)
fig, ax = plt.subplots(figsize=(10, 6))
# 生成并绘制数据
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)')
# 自定义
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('Trigonometric Functions')
ax.legend()
ax.grid(True, alpha=0.3)
# 保存和/或显示
plt.savefig('plot.png', dpi=300, bbox_inches='tight')
plt.show()
创建子图布局:
# 方法 1:规则网格
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)
# 方法 2:马赛克布局(更灵活)
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)
# 方法 3:GridSpec(最大控制)
from matplotlib.gridspec import GridSpec
fig = plt.figure(figsize=(12, 8))
gs = GridSpec(3, 3, figure=fig)
ax1 = fig.add_subplot(gs[0, :]) # 顶行,所有列
ax2 = fig.add_subplot(gs[1:, 0]) # 底部两行,第一列
ax3 = fig.add_subplot(gs[1:, 1:]) # 底部两行,最后两列
折线图 - 时间序列、连续数据、趋势
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')
# 对于水平条形图:
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。
颜色指定方法:
'red'、'blue'、'steelblue''#FF5733'(0.1, 0.2, 0.3)cmap='viridis'、cmap='plasma'、cmap='coolwarm'使用样式表:
plt.style.use('seaborn-v0_8-darkgrid') # 应用预定义样式
# 可用样式:'ggplot'、'bmh'、'fivethirtyeight' 等。
print(plt.style.available) # 列出所有可用样式
使用 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。
导出为各种格式:
# 用于演示/论文的高分辨率 PNG
plt.savefig('figure.png', dpi=300, bbox_inches='tight', facecolor='white')
# 用于出版物的矢量格式(可缩放)
plt.savefig('figure.pdf', bbox_inches='tight')
plt.savefig('figure.svg', bbox_inches='tight')
# 透明背景
plt.savefig('figure.png', dpi=300, bbox_inches='tight', transparent=True)
重要参数:
dpi:分辨率(出版物用 300,网页用 150,屏幕用 72)bbox_inches='tight':移除多余空白facecolor='white':确保白色背景(对透明主题有用)transparent=True:透明背景from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
# 曲面图
ax.plot_surface(X, Y, Z, cmap='viridis')
# 3D 散点图
ax.scatter(x, y, z, c=colors, marker='o')
# 3D 折线图
ax.plot(x, y, z, linewidth=2)
# 标签
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
fig, ax = plt.subplots(figsize=(10, 6))constrained_layout=True 或 tight_layout() 防止元素重叠fig, ax = plt.subplots(constrained_layout=True) 进行自动间距调整rasterized=True 以减少文件大小# 良好实践:清晰的结构
def create_analysis_plot(data, title):
"""创建标准化的分析图表。"""
fig, ax = plt.subplots(figsize=(10, 6), constrained_layout=True)
# 绘制数据
ax.plot(data['x'], data['y'], linewidth=2)
# 自定义
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
# 使用函数
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 与以下工具集成良好:
%matplotlib inline 或 %matplotlib widget 进行交互式绘图constrained_layout=True 或 tight_layout()plt.close(fig) 显式关闭图形plt.rcParams['font.sans-serif'] 抑制警告pixels = dpi * inches每周安装次数
295
仓库
GitHub 星标数
22.6K
首次出现
Jan 21, 2026
安全审计
安装在
opencode242
gemini-cli193
claude-code192
codex190
cursor180
github-copilot175
Matplotlib is Python's foundational visualization library for creating static, animated, and interactive plots. This skill provides guidance on using matplotlib effectively, covering both the pyplot interface (MATLAB-style) and the object-oriented API (Figure/Axes), along with best practices for creating publication-quality visualizations.
This skill should be used when:
Matplotlib uses a hierarchical structure of objects:
1. pyplot Interface (Implicit, MATLAB-style)
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()
2. Object-Oriented Interface (Explicit)
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4])
ax.set_ylabel('some numbers')
plt.show()
Single plot workflow:
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()
Creating subplot layouts:
# 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
Line plots - Time series, continuous data, trends
ax.plot(x, y, linewidth=2, linestyle='--', marker='o', color='blue')
Scatter plots - Relationships between variables, correlations
ax.scatter(x, y, s=sizes, c=colors, alpha=0.6, cmap='viridis')
Bar charts - Categorical comparisons
ax.bar(categories, values, color='steelblue', edgecolor='black')
# For horizontal bars:
ax.barh(categories, values)
Histograms - Distributions
ax.hist(data, bins=30, edgecolor='black', alpha=0.7)
Heatmaps - Matrix data, correlations
im = ax.imshow(matrix, cmap='coolwarm', aspect='auto')
plt.colorbar(im, ax=ax)
Contour plots - 3D data on 2D plane
contour = ax.contour(X, Y, Z, levels=10)
ax.clabel(contour, inline=True, fontsize=8)
Box plots - Statistical distributions
ax.boxplot([data1, data2, data3], labels=['A', 'B', 'C'])
Violin plots - Distribution densities
ax.violinplot([data1, data2, data3], positions=[1, 2, 3])
For comprehensive plot type examples and variations, refer to references/plot_types.md.
Color specification methods:
'red', 'blue', 'steelblue''#FF5733'(0.1, 0.2, 0.3)cmap='viridis', cmap='plasma', cmap='coolwarm'Using style sheets:
plt.style.use('seaborn-v0_8-darkgrid') # Apply predefined style
# Available styles: 'ggplot', 'bmh', 'fivethirtyeight', etc.
print(plt.style.available) # List all available styles
Customizing with 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
Text and annotations:
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'))
For detailed styling options and colormap guidelines, see references/styling_guide.md.
Export to various formats:
# 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)
Important parameters:
dpi: Resolution (300 for publications, 150 for web, 72 for screen)bbox_inches='tight': Removes excess whitespacefacecolor='white': Ensures white background (useful for transparent themes)transparent=True: Transparent backgroundfrom 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')
fig, ax = plt.subplots(figsize=(10, 6))constrained_layout=True or tight_layout() to prevent overlapping elementsfig, ax = plt.subplots(constrained_layout=True) is recommended for automatic spacingrasterized=True in plot calls to reduce file size# 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')
This skill includes helper scripts in the scripts/ directory:
plot_template.pyTemplate script demonstrating various plot types with best practices. Use this as a starting point for creating new visualizations.
Usage:
python scripts/plot_template.py
style_configurator.pyInteractive utility to configure matplotlib style preferences and generate custom style sheets.
Usage:
python scripts/style_configurator.py
For comprehensive information, consult the reference documents:
references/plot_types.md - Complete catalog of plot types with code examples and use casesreferences/styling_guide.md - Detailed styling options, colormaps, and customizationreferences/api_reference.md - Core classes and methods referencereferences/common_issues.md - Troubleshooting guide for common problemsMatplotlib integrates well with:
%matplotlib inline or %matplotlib widgetconstrained_layout=True or tight_layout()plt.close(fig)plt.rcParams['font.sans-serif']pixels = dpi * inchesWeekly Installs
295
Repository
GitHub Stars
22.6K
First Seen
Jan 21, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode242
gemini-cli193
claude-code192
codex190
cursor180
github-copilot175
DOCX文件创建、编辑与分析完整指南 - 使用docx-js、Pandoc和Python脚本
43,600 周安装