matplotlib-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMatplotlib Best Practices
Matplotlib 最佳实践
Expert guidelines for Matplotlib development, focusing on data visualization, plotting, and creating publication-quality figures.
Matplotlib开发的专家指南,聚焦于数据可视化、绘图及生成出版级图表。
Code Style and Structure
代码风格与结构
- Write concise, technical Python code with accurate Matplotlib examples
- Create informative and visually appealing plots with proper labels, titles, and legends
- Use the object-oriented API for complex figures, pyplot for quick plots
- Follow PEP 8 style guidelines
- Consider color-blindness accessibility in all visualizations
- 编写简洁、专业的Python代码,搭配准确的Matplotlib示例
- 创建带有恰当标签、标题和图例的信息丰富且视觉美观的图表
- 针对复杂图表使用面向对象API,快速绘图使用pyplot
- 遵循PEP 8风格指南
- 在所有可视化中考虑色盲友好的可访问性
API Approaches
API 方法
Object-Oriented Interface (Recommended)
面向对象接口(推荐)
- Use for explicit control
fig, ax = plt.subplots() - Preferred for complex figures and production code
- Methods are called on axes objects: ,
ax.plot()ax.set_xlabel() - Enables multiple subplots and fine-grained customization
- 使用实现显式控制
fig, ax = plt.subplots() - 适用于复杂图表和生产代码
- 方法调用在轴对象上:、
ax.plot()ax.set_xlabel() - 支持多子图和精细化定制
Pyplot Interface
Pyplot 接口
- Use ,
plt.plot()for quick, interactive plotsplt.xlabel() - Suitable for Jupyter notebooks and exploration
- Use in Jupyter notebooks
%matplotlib inline
- 使用、
plt.plot()进行快速交互式绘图plt.xlabel() - 适用于Jupyter笔记本和探索性分析
- 在Jupyter笔记本中使用
%matplotlib inline
Creating Effective Visualizations
创建高效可视化
Plot Types and Selection
图表类型选择
- Line plots () for continuous data and trends
ax.plot() - Scatter plots () for relationship between variables
ax.scatter() - Bar plots (,
ax.bar()) for categorical comparisonsax.barh() - Histograms () for distributions
ax.hist() - Box plots () for statistical summaries
ax.boxplot() - Heatmaps (,
ax.imshow()) for 2D dataax.pcolormesh()
- 折线图()用于展示连续数据和趋势
ax.plot() - 散点图()用于展示变量间的关系
ax.scatter() - 柱状图(、
ax.bar())用于分类比较ax.barh() - 直方图()用于展示分布情况
ax.hist() - 箱线图()用于统计摘要
ax.boxplot() - 热力图(、
ax.imshow())用于二维数据ax.pcolormesh()
Labels and Annotations
标签与注释
- Always include axis labels with units
- Use descriptive titles that convey the message
- Add legends when multiple series are present
- Use annotations () to highlight key points
ax.annotate() - Include data source attribution when appropriate
- 始终包含带单位的轴标签
- 使用能传达核心信息的描述性标题
- 当存在多个系列时添加图例
- 使用注释()突出关键点
ax.annotate() - 适当情况下注明数据来源
Color and Style
颜色与样式
- Use colorblind-friendly palettes (e.g., 'viridis', 'plasma', 'cividis')
- Avoid red-green combinations for accessibility
- Use consistent colors for the same categories across figures
- Use appropriate colormaps for data type:
- Sequential: 'viridis', 'plasma' for continuous data
- Diverging: 'RdBu', 'coolwarm' for data with meaningful center
- Qualitative: 'Set1', 'tab10' for categorical data
- 使用色盲友好的调色板(如'viridis'、'plasma'、'cividis')
- 避免使用红绿色组合以保障可访问性
- 在不同图表中为同一类别使用一致的颜色
- 根据数据类型选择合适的颜色映射:
- 连续型:'viridis'、'plasma' 适用于连续数据
- 发散型:'RdBu'、'coolwarm' 适用于有意义中心值的数据
- 定性型:'Set1'、'tab10' 适用于分类数据
Figure Layout and Composition
图表布局与构图
Subplots
子图
- Use for grid layouts
plt.subplots(nrows, ncols) - Use for complex, non-uniform layouts
gridspec - Share axes with ,
sharex=Truefor comparisonsharey=True - Use or
constrained_layout=Trueto prevent overlaptight_layout()
- 使用创建网格布局
plt.subplots(nrows, ncols) - 使用创建复杂的非均匀布局
gridspec - 使用、
sharex=True共享轴以方便比较sharey=True - 使用或
constrained_layout=True防止元素重叠tight_layout()
Figure Size and Resolution
图表尺寸与分辨率
- Set figure size explicitly: in inches
figsize=(width, height) - Use appropriate DPI for intended output (72 screen, 300+ print)
- Standard sizes: (10, 6) for presentations, (8, 6) for papers
- 显式设置图表尺寸:,单位为英寸
figsize=(width, height) - 根据预期输出选择合适的DPI(屏幕用72,印刷用300+)
- 标准尺寸:演示文稿用(10, 6),论文用(8, 6)
Customization
定制化
Style Sheets
样式表
- Use built-in styles: ,
plt.style.use('seaborn-v0_8')'ggplot' - Create custom style files for consistent branding
- Combine styles:
plt.style.use(['seaborn-v0_8', 'custom.mplstyle'])
- 使用内置样式:、
plt.style.use('seaborn-v0_8')'ggplot' - 创建自定义样式文件以保持品牌一致性
- 组合样式:
plt.style.use(['seaborn-v0_8', 'custom.mplstyle'])
Text and Fonts
文本与字体
- Use LaTeX for mathematical notation:
r'$\alpha = \frac{1}{2}$' - Set font family for consistency
- Adjust font sizes for readability at intended display size
- 使用LaTeX表示数学符号:
r'$\alpha = \frac{1}{2}$' - 设置统一的字体族
- 根据预期显示尺寸调整字体大小以保障可读性
Saving and Exporting
保存与导出
File Formats
文件格式
- Use vector formats (PDF, SVG, EPS) for publications
- Use PNG for web and presentations with transparency
- Use JPEG only for photographs (lossy compression)
- 出版用矢量格式(PDF、SVG、EPS)
- 网页和演示文稿用PNG(支持透明)
- 仅在处理照片时使用JPEG(有损压缩)
Export Settings
导出设置
- Use to remove excess whitespace
bbox_inches='tight' - Set for background color
facecolor - Specify appropriate for use case
dpi - Use for overlays
transparent=True
- 使用去除多余空白
bbox_inches='tight' - 设置指定背景色
facecolor - 根据使用场景指定
dpi - 使用创建叠加层
transparent=True
Performance Optimization
性能优化
- Use for scatter plots with many points
rasterized=True - Consider downsampling data for visualization
- Close figures with after saving
plt.close() - Use in loops creating many figures
plt.close('all')
- 对包含大量点的散点图使用
rasterized=True - 考虑对数据进行下采样后再可视化
- 保存后使用关闭图表
plt.close() - 在循环创建大量图表时使用
plt.close('all')
Key Conventions
关键约定
- Import as
import matplotlib.pyplot as plt - Use object-oriented API for production code
- Always label axes and include units
- Test visualizations at intended display size
- Consider accessibility in color choices
- 导入方式为
import matplotlib.pyplot as plt - 生产代码使用面向对象API
- 始终为轴添加标签并包含单位
- 在预期显示尺寸下测试可视化效果
- 颜色选择时考虑可访问性