matplotlib-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Matplotlib 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
    fig, ax = plt.subplots()
    for explicit control
  • 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()
    ,
    plt.xlabel()
    for quick, interactive plots
  • Suitable for Jupyter notebooks and exploration
  • Use
    %matplotlib inline
    in Jupyter notebooks
  • 使用
    plt.plot()
    plt.xlabel()
    进行快速交互式绘图
  • 适用于Jupyter笔记本和探索性分析
  • 在Jupyter笔记本中使用
    %matplotlib inline

Creating Effective Visualizations

创建高效可视化

Plot Types and Selection

图表类型选择

  • Line plots (
    ax.plot()
    ) for continuous data and trends
  • Scatter plots (
    ax.scatter()
    ) for relationship between variables
  • Bar plots (
    ax.bar()
    ,
    ax.barh()
    ) for categorical comparisons
  • Histograms (
    ax.hist()
    ) for distributions
  • Box plots (
    ax.boxplot()
    ) for statistical summaries
  • Heatmaps (
    ax.imshow()
    ,
    ax.pcolormesh()
    ) for 2D data
  • 折线图(
    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 (
    ax.annotate()
    ) to highlight key points
  • 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
    plt.subplots(nrows, ncols)
    for grid layouts
  • Use
    gridspec
    for complex, non-uniform layouts
  • Share axes with
    sharex=True
    ,
    sharey=True
    for comparison
  • Use
    constrained_layout=True
    or
    tight_layout()
    to prevent overlap
  • 使用
    plt.subplots(nrows, ncols)
    创建网格布局
  • 使用
    gridspec
    创建复杂的非均匀布局
  • 使用
    sharex=True
    sharey=True
    共享轴以方便比较
  • 使用
    constrained_layout=True
    tight_layout()
    防止元素重叠

Figure Size and Resolution

图表尺寸与分辨率

  • Set figure size explicitly:
    figsize=(width, height)
    in inches
  • 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
    bbox_inches='tight'
    to remove excess whitespace
  • Set
    facecolor
    for background color
  • Specify
    dpi
    appropriate for use case
  • Use
    transparent=True
    for overlays
  • 使用
    bbox_inches='tight'
    去除多余空白
  • 设置
    facecolor
    指定背景色
  • 根据使用场景指定
    dpi
  • 使用
    transparent=True
    创建叠加层

Performance Optimization

性能优化

  • Use
    rasterized=True
    for scatter plots with many points
  • Consider downsampling data for visualization
  • Close figures with
    plt.close()
    after saving
  • Use
    plt.close('all')
    in loops creating many figures
  • 对包含大量点的散点图使用
    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
  • 始终为轴添加标签并包含单位
  • 在预期显示尺寸下测试可视化效果
  • 颜色选择时考虑可访问性