scientific-visualization

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Scientific Visualization

科学可视化

Overview

概述

Scientific visualization transforms data into clear, accurate figures for publication. Create journal-ready plots with multi-panel layouts, error bars, significance markers, and colorblind-safe palettes. Export as PDF/EPS/TIFF using matplotlib, seaborn, and plotly for manuscripts.
科学可视化将数据转化为清晰、准确的可发表图表。使用matplotlib、seaborn和plotly创建支持多面板布局、误差棒、显著性标记、色盲友好配色的期刊级图表,并导出为PDF/EPS/TIFF格式用于学术稿件。

When to Use This Skill

适用场景

This skill should be used when:
  • Creating plots or visualizations for scientific manuscripts
  • Preparing figures for journal submission (Nature, Science, Cell, PLOS, etc.)
  • Ensuring figures are colorblind-friendly and accessible
  • Making multi-panel figures with consistent styling
  • Exporting figures at correct resolution and format
  • Following specific publication guidelines
  • Improving existing figures to meet publication standards
  • Creating figures that need to work in both color and grayscale
本技能适用于以下场景:
  • 为学术稿件创建图表或可视化内容
  • 准备用于期刊投稿的图表(如《自然》《科学》《细胞》《PLOS》等)
  • 确保图表对色盲人群友好且具备可访问性
  • 创建样式统一的多面板图表
  • 以正确的分辨率和格式导出图表
  • 遵循特定期刊的发表指南
  • 优化现有图表以达到发表标准
  • 创建同时适用于彩色和灰度显示的图表

Quick Start Guide

快速入门指南

Basic Publication-Quality Figure

基础期刊级图表

python
import matplotlib.pyplot as plt
import numpy as np
python
import matplotlib.pyplot as plt
import numpy as np

Apply publication style (from scripts/style_presets.py)

应用发表样式(来自scripts/style_presets.py)

from style_presets import apply_publication_style apply_publication_style('default')
from style_presets import apply_publication_style apply_publication_style('default')

Create figure with appropriate size (single column = 3.5 inches)

创建合适尺寸的图表(单栏 = 3.5英寸)

fig, ax = plt.subplots(figsize=(3.5, 2.5))
fig, ax = plt.subplots(figsize=(3.5, 2.5))

Plot data

绘制数据

x = np.linspace(0, 10, 100) ax.plot(x, np.sin(x), label='sin(x)') ax.plot(x, np.cos(x), label='cos(x)')
x = np.linspace(0, 10, 100) ax.plot(x, np.sin(x), label='sin(x)') ax.plot(x, np.cos(x), label='cos(x)')

Proper labeling with units

添加带单位的规范标签

ax.set_xlabel('Time (seconds)') ax.set_ylabel('Amplitude (mV)') ax.legend(frameon=False)
ax.set_xlabel('Time (seconds)') ax.set_ylabel('Amplitude (mV)') ax.legend(frameon=False)

Remove unnecessary spines

移除不必要的边框

ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False)

Save in publication formats (from scripts/figure_export.py)

保存为发表格式(来自scripts/figure_export.py)

from figure_export import save_publication_figure save_publication_figure(fig, 'figure1', formats=['pdf', 'png'], dpi=300)
undefined
from figure_export import save_publication_figure save_publication_figure(fig, 'figure1', formats=['pdf', 'png'], dpi=300)
undefined

Using Pre-configured Styles

使用预配置样式

Apply journal-specific styles using the matplotlib style files in
assets/
:
python
import matplotlib.pyplot as plt
使用
assets/
目录中的matplotlib样式文件应用期刊专属样式:
python
import matplotlib.pyplot as plt

Option 1: Use style file directly

方式1:直接使用样式文件

plt.style.use('assets/nature.mplstyle')
plt.style.use('assets/nature.mplstyle')

Option 2: Use style_presets.py helper

方式2:使用style_presets.py辅助工具

from style_presets import configure_for_journal configure_for_journal('nature', figure_width='single')
from style_presets import configure_for_journal configure_for_journal('nature', figure_width='single')

Now create figures - they'll automatically match Nature specifications

现在创建的图表将自动匹配《自然》期刊的规范

fig, ax = plt.subplots()
fig, ax = plt.subplots()

... your plotting code ...

... 你的绘图代码 ...

undefined
undefined

Quick Start with Seaborn

Seaborn快速入门

For statistical plots, use seaborn with publication styling:
python
import seaborn as sns
import matplotlib.pyplot as plt
from style_presets import apply_publication_style
对于统计图表,结合发表样式使用seaborn:
python
import seaborn as sns
import matplotlib.pyplot as plt
from style_presets import apply_publication_style

Apply publication style

应用发表样式

apply_publication_style('default') sns.set_theme(style='ticks', context='paper', font_scale=1.1) sns.set_palette('colorblind')
apply_publication_style('default') sns.set_theme(style='ticks', context='paper', font_scale=1.1) sns.set_palette('colorblind')

Create statistical comparison figure

创建统计对比图表

fig, ax = plt.subplots(figsize=(3.5, 3)) sns.boxplot(data=df, x='treatment', y='response', order=['Control', 'Low', 'High'], palette='Set2', ax=ax) sns.stripplot(data=df, x='treatment', y='response', order=['Control', 'Low', 'High'], color='black', alpha=0.3, size=3, ax=ax) ax.set_ylabel('Response (μM)') sns.despine()
fig, ax = plt.subplots(figsize=(3.5, 3)) sns.boxplot(data=df, x='treatment', y='response', order=['Control', 'Low', 'High'], palette='Set2', ax=ax) sns.stripplot(data=df, x='treatment', y='response', order=['Control', 'Low', 'High'], color='black', alpha=0.3, size=3, ax=ax) ax.set_ylabel('Response (μM)') sns.despine()

Save figure

保存图表

from figure_export import save_publication_figure save_publication_figure(fig, 'treatment_comparison', formats=['pdf', 'png'], dpi=300)
undefined
from figure_export import save_publication_figure save_publication_figure(fig, 'treatment_comparison', formats=['pdf', 'png'], dpi=300)
undefined

Core Principles and Best Practices

核心原则与最佳实践

1. Resolution and File Format

1. 分辨率与文件格式

Critical requirements (detailed in
references/publication_guidelines.md
):
  • Raster images (photos, microscopy): 300-600 DPI
  • Line art (graphs, plots): 600-1200 DPI or vector format
  • Vector formats (preferred): PDF, EPS, SVG
  • Raster formats: TIFF, PNG (never JPEG for scientific data)
Implementation:
python
undefined
关键要求(详见
references/publication_guidelines.md
):
  • 光栅图像(照片、显微图像):300-600 DPI
  • 线条图(统计图、曲线图):600-1200 DPI或矢量格式
  • 推荐矢量格式:PDF、EPS、SVG
  • 光栅格式:TIFF、PNG(科学数据绝对不要用JPEG)
实现方式:
python
undefined

Use the figure_export.py script for correct settings

使用figure_export.py脚本设置正确参数

from figure_export import save_publication_figure
from figure_export import save_publication_figure

Saves in multiple formats with proper DPI

以合适的DPI保存为多种格式

save_publication_figure(fig, 'myfigure', formats=['pdf', 'png'], dpi=300)
save_publication_figure(fig, 'myfigure', formats=['pdf', 'png'], dpi=300)

Or save for specific journal requirements

或针对特定期刊要求保存

from figure_export import save_for_journal save_for_journal(fig, 'figure1', journal='nature', figure_type='combination')
undefined
from figure_export import save_for_journal save_for_journal(fig, 'figure1', journal='nature', figure_type='combination')
undefined

2. Color Selection - Colorblind Accessibility

2. 颜色选择——色盲可访问性

Always use colorblind-friendly palettes (detailed in
references/color_palettes.md
):
Recommended: Okabe-Ito palette (distinguishable by all types of color blindness):
python
undefined
务必使用色盲友好配色方案(详见
references/color_palettes.md
):
推荐:Okabe-Ito配色方案(所有类型色盲人群均可区分):
python
undefined

Option 1: Use assets/color_palettes.py

方式1:使用assets/color_palettes.py

from color_palettes import OKABE_ITO_LIST, apply_palette apply_palette('okabe_ito')
from color_palettes import OKABE_ITO_LIST, apply_palette apply_palette('okabe_ito')

Option 2: Manual specification

方式2:手动指定

okabe_ito = ['#E69F00', '#56B4E9', '#009E73', '#F0E442', '#0072B2', '#D55E00', '#CC79A7', '#000000'] plt.rcParams['axes.prop_cycle'] = plt.cycler(color=okabe_ito)

**For heatmaps/continuous data:**
- Use perceptually uniform colormaps: `viridis`, `plasma`, `cividis`
- Avoid red-green diverging maps (use `PuOr`, `RdBu`, `BrBG` instead)
- Never use `jet` or `rainbow` colormaps

**Always test figures in grayscale** to ensure interpretability.
okabe_ito = ['#E69F00', '#56B4E9', '#009E73', '#F0E442', '#0072B2', '#D55E00', '#CC79A7', '#000000'] plt.rcParams['axes.prop_cycle'] = plt.cycler(color=okabe_ito)

**针对热力图/连续数据:**
- 使用感知均匀的颜色映射:`viridis`、`plasma`、`cividis`
- 避免红绿色发散映射(改用`PuOr`、`RdBu`、`BrBG`)
- 绝对不要使用`jet`或`rainbow`颜色映射

**务必测试图表的灰度显示效果**,确保可解读性。

3. Typography and Text

3. 排版与文本

Font guidelines (detailed in
references/publication_guidelines.md
):
  • Sans-serif fonts: Arial, Helvetica, Calibri
  • Minimum sizes at final print size:
    • Axis labels: 7-9 pt
    • Tick labels: 6-8 pt
    • Panel labels: 8-12 pt (bold)
  • Sentence case for labels: "Time (hours)" not "TIME (HOURS)"
  • Always include units in parentheses
Implementation:
python
undefined
字体指南(详见
references/publication_guidelines.md
):
  • 无衬线字体:Arial、Helvetica、Calibri
  • 最终打印尺寸下的最小字号:
    • 坐标轴标签:7-9 pt
    • 刻度标签:6-8 pt
    • 面板标签:8-12 pt(加粗)
  • 标签采用句首大写格式:"Time (hours)" 而非 "TIME (HOURS)"
  • 务必在括号中注明单位
实现方式:
python
undefined

Set fonts globally

全局设置字体

import matplotlib as mpl mpl.rcParams['font.family'] = 'sans-serif' mpl.rcParams['font.sans-serif'] = ['Arial', 'Helvetica'] mpl.rcParams['font.size'] = 8 mpl.rcParams['axes.labelsize'] = 9 mpl.rcParams['xtick.labelsize'] = 7 mpl.rcParams['ytick.labelsize'] = 7
undefined
import matplotlib as mpl mpl.rcParams['font.family'] = 'sans-serif' mpl.rcParams['font.sans-serif'] = ['Arial', 'Helvetica'] mpl.rcParams['font.size'] = 8 mpl.rcParams['axes.labelsize'] = 9 mpl.rcParams['xtick.labelsize'] = 7 mpl.rcParams['ytick.labelsize'] = 7
undefined

4. Figure Dimensions

4. 图表尺寸

Journal-specific widths (detailed in
references/journal_requirements.md
):
  • Nature: Single 89 mm, Double 183 mm
  • Science: Single 55 mm, Double 175 mm
  • Cell: Single 85 mm, Double 178 mm
Check figure size compliance:
python
from figure_export import check_figure_size

fig = plt.figure(figsize=(3.5, 3))  # 89 mm for Nature
check_figure_size(fig, journal='nature')
期刊专属宽度(详见
references/journal_requirements.md
):
  • 《自然》:单栏89毫米,双栏183毫米
  • 《科学》:单栏55毫米,双栏175毫米
  • 《细胞》:单栏85毫米,双栏178毫米
检查图表尺寸合规性:
python
from figure_export import check_figure_size

fig = plt.figure(figsize=(3.5, 3))  # 《自然》期刊单栏尺寸(89毫米)
check_figure_size(fig, journal='nature')

5. Multi-Panel Figures

5. 多面板图表

Best practices:
  • Label panels with bold letters: A, B, C (uppercase for most journals, lowercase for Nature)
  • Maintain consistent styling across all panels
  • Align panels along edges where possible
  • Use adequate white space between panels
Example implementation (see
references/matplotlib_examples.md
for complete code):
python
from string import ascii_uppercase

fig = plt.figure(figsize=(7, 4))
gs = fig.add_gridspec(2, 2, hspace=0.4, wspace=0.4)

ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1])
最佳实践:
  • 使用加粗字母标注面板:ABC(多数期刊用大写,《自然》用小写)
  • 所有面板保持统一样式
  • 尽可能对齐面板边缘
  • 面板间保留足够留白
示例实现(完整代码见
references/matplotlib_examples.md
):
python
from string import ascii_uppercase

fig = plt.figure(figsize=(7, 4))
gs = fig.add_gridspec(2, 2, hspace=0.4, wspace=0.4)

ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1])

... create other panels ...

... 创建其他面板 ...

Add panel labels

添加面板标签

for i, ax in enumerate([ax1, ax2, ...]): ax.text(-0.15, 1.05, ascii_uppercase[i], transform=ax.transAxes, fontsize=10, fontweight='bold', va='top')
undefined
for i, ax in enumerate([ax1, ax2, ...]): ax.text(-0.15, 1.05, ascii_uppercase[i], transform=ax.transAxes, fontsize=10, fontweight='bold', va='top')
undefined

Common Tasks

常见任务

Task 1: Create a Publication-Ready Line Plot

任务1:创建期刊级折线图

See
references/matplotlib_examples.md
Example 1 for complete code.
Key steps:
  1. Apply publication style
  2. Set appropriate figure size for target journal
  3. Use colorblind-friendly colors
  4. Add error bars with correct representation (SEM, SD, or CI)
  5. Label axes with units
  6. Remove unnecessary spines
  7. Save in vector format
Using seaborn for automatic confidence intervals:
python
import seaborn as sns
fig, ax = plt.subplots(figsize=(5, 3))
sns.lineplot(data=timeseries, x='time', y='measurement',
             hue='treatment', errorbar=('ci', 95), 
             markers=True, ax=ax)
ax.set_xlabel('Time (hours)')
ax.set_ylabel('Measurement (AU)')
sns.despine()
完整代码见
references/matplotlib_examples.md
示例1。
关键步骤:
  1. 应用发表样式
  2. 根据目标期刊设置合适的图表尺寸
  3. 使用色盲友好配色
  4. 添加正确的误差棒(标准误、标准差或置信区间)
  5. 为坐标轴添加带单位的标签
  6. 移除不必要的边框
  7. 保存为矢量格式
使用seaborn自动生成置信区间:
python
import seaborn as sns
fig, ax = plt.subplots(figsize=(5, 3))
sns.lineplot(data=timeseries, x='time', y='measurement',
             hue='treatment', errorbar=('ci', 95), 
             markers=True, ax=ax)
ax.set_xlabel('Time (hours)')
ax.set_ylabel('Measurement (AU)')
sns.despine()

Task 2: Create a Multi-Panel Figure

任务2:创建多面板图表

See
references/matplotlib_examples.md
Example 2 for complete code.
Key steps:
  1. Use
    GridSpec
    for flexible layout
  2. Ensure consistent styling across panels
  3. Add bold panel labels (A, B, C, etc.)
  4. Align related panels
  5. Verify all text is readable at final size
完整代码见
references/matplotlib_examples.md
示例2。
关键步骤:
  1. 使用
    GridSpec
    实现灵活布局
  2. 确保所有面板样式统一
  3. 添加加粗面板标签(A、B、C等)
  4. 对齐相关面板
  5. 验证所有文本在最终尺寸下可读

Task 3: Create a Heatmap with Proper Colormap

任务3:创建配色规范的热力图

See
references/matplotlib_examples.md
Example 4 for complete code.
Key steps:
  1. Use perceptually uniform colormap (
    viridis
    ,
    plasma
    ,
    cividis
    )
  2. Include labeled colorbar
  3. For diverging data, use colorblind-safe diverging map (
    RdBu_r
    ,
    PuOr
    )
  4. Set appropriate center value for diverging maps
  5. Test appearance in grayscale
Using seaborn for correlation matrices:
python
import seaborn as sns
fig, ax = plt.subplots(figsize=(5, 4))
corr = df.corr()
mask = np.triu(np.ones_like(corr, dtype=bool))
sns.heatmap(corr, mask=mask, annot=True, fmt='.2f',
            cmap='RdBu_r', center=0, square=True,
            linewidths=1, cbar_kws={'shrink': 0.8}, ax=ax)
完整代码见
references/matplotlib_examples.md
示例4。
关键步骤:
  1. 使用感知均匀的颜色映射(
    viridis
    plasma
    cividis
  2. 添加带标签的颜色条
  3. 针对发散数据,使用色盲友好的发散映射(
    RdBu_r
    PuOr
  4. 为发散映射设置合适的中心值
  5. 测试灰度显示效果
使用seaborn绘制相关矩阵:
python
import seaborn as sns
fig, ax = plt.subplots(figsize=(5, 4))
corr = df.corr()
mask = np.triu(np.ones_like(corr, dtype=bool))
sns.heatmap(corr, mask=mask, annot=True, fmt='.2f',
            cmap='RdBu_r', center=0, square=True,
            linewidths=1, cbar_kws={'shrink': 0.8}, ax=ax)

Task 4: Prepare Figure for Specific Journal

任务4:为特定期刊准备图表

Workflow:
  1. Check journal requirements:
    references/journal_requirements.md
  2. Configure matplotlib for journal:
    python
    from style_presets import configure_for_journal
    configure_for_journal('nature', figure_width='single')
  3. Create figure (will auto-size correctly)
  4. Export with journal specifications:
    python
    from figure_export import save_for_journal
    save_for_journal(fig, 'figure1', journal='nature', figure_type='line_art')
工作流程:
  1. 查看期刊要求:
    references/journal_requirements.md
  2. 为期刊配置matplotlib:
    python
    from style_presets import configure_for_journal
    configure_for_journal('nature', figure_width='single')
  3. 创建图表(将自动匹配尺寸)
  4. 按照期刊规范导出:
    python
    from figure_export import save_for_journal
    save_for_journal(fig, 'figure1', journal='nature', figure_type='line_art')

Task 5: Fix an Existing Figure to Meet Publication Standards

任务5:优化现有图表以达到发表标准

Checklist approach (full checklist in
references/publication_guidelines.md
):
  1. Check resolution: Verify DPI meets journal requirements
  2. Check file format: Use vector for plots, TIFF/PNG for images
  3. Check colors: Ensure colorblind-friendly
  4. Check fonts: Minimum 6-7 pt at final size, sans-serif
  5. Check labels: All axes labeled with units
  6. Check size: Matches journal column width
  7. Test grayscale: Figure interpretable without color
  8. Remove chart junk: No unnecessary grids, 3D effects, shadows
清单检查法(完整清单见
references/publication_guidelines.md
):
  1. 检查分辨率:验证DPI符合期刊要求
  2. 检查文件格式:图表使用矢量格式,图像使用TIFF/PNG
  3. 检查配色:确保色盲友好
  4. 检查字体:最终尺寸下最小字号6-7 pt,使用无衬线字体
  5. 检查标签:所有坐标轴均标注单位
  6. 检查尺寸:匹配期刊栏宽
  7. 测试灰度显示:图表无需颜色即可解读
  8. 移除冗余元素:删除不必要的网格、3D效果、阴影

Task 6: Create Colorblind-Friendly Visualizations

任务6:创建色盲友好的可视化内容

Strategy:
  1. Use approved palettes from
    assets/color_palettes.py
  2. Add redundant encoding (line styles, markers, patterns)
  3. Test with colorblind simulator
  4. Ensure grayscale compatibility
Example:
python
from color_palettes import apply_palette
import matplotlib.pyplot as plt

apply_palette('okabe_ito')
策略:
  1. 使用
    assets/color_palettes.py
    中的推荐配色方案
  2. 添加冗余编码(线条样式、标记、图案)
  3. 使用色盲模拟器测试
  4. 确保灰度兼容性
示例:
python
from color_palettes import apply_palette
import matplotlib.pyplot as plt

apply_palette('okabe_ito')

Add redundant encoding beyond color

添加颜色之外的冗余编码

line_styles = ['-', '--', '-.', ':'] markers = ['o', 's', '^', 'v']
for i, (data, label) in enumerate(datasets): plt.plot(x, data, linestyle=line_styles[i % 4], marker=markers[i % 4], label=label)
undefined
line_styles = ['-', '--', '-.', ':'] markers = ['o', 's', '^', 'v']
for i, (data, label) in enumerate(datasets): plt.plot(x, data, linestyle=line_styles[i % 4], marker=markers[i % 4], label=label)
undefined

Statistical Rigor

统计严谨性

Always include:
  • Error bars (SD, SEM, or CI - specify which in caption)
  • Sample size (n) in figure or caption
  • Statistical significance markers (*, **, ***)
  • Individual data points when possible (not just summary statistics)
Example with statistics:
python
undefined
务必包含:
  • 误差棒(标准差、标准误或置信区间——在图注中说明类型)
  • 样本量(n)——标注在图表或图注中
  • 统计显著性标记(
  • 尽可能展示单个数据点(而非仅汇总统计量)
含统计信息的示例:
python
undefined

Show individual points with summary statistics

展示单个数据点与汇总统计量

ax.scatter(x_jittered, individual_points, alpha=0.4, s=8) ax.errorbar(x, means, yerr=sems, fmt='o', capsize=3)
ax.scatter(x_jittered, individual_points, alpha=0.4, s=8) ax.errorbar(x, means, yerr=sems, fmt='o', capsize=3)

Mark significance

标记显著性

ax.text(1.5, max_y * 1.1, '***', ha='center', fontsize=8)
undefined
ax.text(1.5, max_y * 1.1, '***', ha='center', fontsize=8)
undefined

Working with Different Plotting Libraries

不同绘图库的使用

Matplotlib

Matplotlib

  • Most control over publication details
  • Best for complex multi-panel figures
  • Use provided style files for consistent formatting
  • See
    references/matplotlib_examples.md
    for extensive examples
  • 对发表细节的控制程度最高
  • 最适合复杂多面板图表
  • 使用提供的样式文件保持格式统一
  • 详细示例见
    references/matplotlib_examples.md

Seaborn

Seaborn

Seaborn provides a high-level, dataset-oriented interface for statistical graphics, built on matplotlib. It excels at creating publication-quality statistical visualizations with minimal code while maintaining full compatibility with matplotlib customization.
Key advantages for scientific visualization:
  • Automatic statistical estimation and confidence intervals
  • Built-in support for multi-panel figures (faceting)
  • Colorblind-friendly palettes by default
  • Dataset-oriented API using pandas DataFrames
  • Semantic mapping of variables to visual properties
Seaborn是基于matplotlib构建的高级、面向数据集的统计图形接口。它只需少量代码即可创建期刊级统计可视化内容,同时完全兼容matplotlib的自定义设置。
科学可视化的核心优势:
  • 自动统计估计与置信区间计算
  • 内置多面板图表支持(分面)
  • 默认使用色盲友好配色方案
  • 基于pandas DataFrames的面向数据集API
  • 将变量语义映射为视觉属性

Quick Start with Publication Style

Seaborn发表样式快速入门

Always apply matplotlib publication styles first, then configure seaborn:
python
import seaborn as sns
import matplotlib.pyplot as plt
from style_presets import apply_publication_style
务必先应用matplotlib发表样式,再配置seaborn:
python
import seaborn as sns
import matplotlib.pyplot as plt
from style_presets import apply_publication_style

Apply publication style

应用发表样式

apply_publication_style('default')
apply_publication_style('default')

Configure seaborn for publication

配置seaborn以适配发表需求

sns.set_theme(style='ticks', context='paper', font_scale=1.1) sns.set_palette('colorblind') # Use colorblind-safe palette
sns.set_theme(style='ticks', context='paper', font_scale=1.1) sns.set_palette('colorblind') # 使用色盲友好配色

Create figure

创建图表

fig, ax = plt.subplots(figsize=(3.5, 2.5)) sns.scatterplot(data=df, x='time', y='response', hue='treatment', style='condition', ax=ax) sns.despine() # Remove top and right spines
undefined
fig, ax = plt.subplots(figsize=(3.5, 2.5)) sns.scatterplot(data=df, x='time', y='response', hue='treatment', style='condition', ax=ax) sns.despine() # 移除顶部和右侧边框
undefined

Common Plot Types for Publications

适用于发表的常见图表类型

Statistical comparisons:
python
undefined
统计对比:
python
undefined

Box plot with individual points for transparency

箱线图搭配单个数据点以提升透明度

fig, ax = plt.subplots(figsize=(3.5, 3)) sns.boxplot(data=df, x='treatment', y='response', order=['Control', 'Low', 'High'], palette='Set2', ax=ax) sns.stripplot(data=df, x='treatment', y='response', order=['Control', 'Low', 'High'], color='black', alpha=0.3, size=3, ax=ax) ax.set_ylabel('Response (μM)') sns.despine()

**Distribution analysis:**
```python
fig, ax = plt.subplots(figsize=(3.5, 3)) sns.boxplot(data=df, x='treatment', y='response', order=['Control', 'Low', 'High'], palette='Set2', ax=ax) sns.stripplot(data=df, x='treatment', y='response', order=['Control', 'Low', 'High'], color='black', alpha=0.3, size=3, ax=ax) ax.set_ylabel('Response (μM)') sns.despine()

**分布分析:**
```python

Violin plot with split comparison

拆分对比的小提琴图

fig, ax = plt.subplots(figsize=(4, 3)) sns.violinplot(data=df, x='timepoint', y='expression', hue='treatment', split=True, inner='quartile', ax=ax) ax.set_ylabel('Gene Expression (AU)') sns.despine()

**Correlation matrices:**
```python
fig, ax = plt.subplots(figsize=(4, 3)) sns.violinplot(data=df, x='timepoint', y='expression', hue='treatment', split=True, inner='quartile', ax=ax) ax.set_ylabel('Gene Expression (AU)') sns.despine()

**相关矩阵:**
```python

Heatmap with proper colormap and annotations

带规范配色和注释的热力图

fig, ax = plt.subplots(figsize=(5, 4)) corr = df.corr() mask = np.triu(np.ones_like(corr, dtype=bool)) # Show only lower triangle sns.heatmap(corr, mask=mask, annot=True, fmt='.2f', cmap='RdBu_r', center=0, square=True, linewidths=1, cbar_kws={'shrink': 0.8}, ax=ax) plt.tight_layout()

**Time series with confidence bands:**
```python
fig, ax = plt.subplots(figsize=(5, 4)) corr = df.corr() mask = np.triu(np.ones_like(corr, dtype=bool)) # 仅显示下三角 sns.heatmap(corr, mask=mask, annot=True, fmt='.2f', cmap='RdBu_r', center=0, square=True, linewidths=1, cbar_kws={'shrink': 0.8}, ax=ax) plt.tight_layout()

**带置信区间的时间序列:**
```python

Line plot with automatic CI calculation

自动计算置信区间的折线图

fig, ax = plt.subplots(figsize=(5, 3)) sns.lineplot(data=timeseries, x='time', y='measurement', hue='treatment', style='replicate', errorbar=('ci', 95), markers=True, dashes=False, ax=ax) ax.set_xlabel('Time (hours)') ax.set_ylabel('Measurement (AU)') sns.despine()
undefined
fig, ax = plt.subplots(figsize=(5, 3)) sns.lineplot(data=timeseries, x='time', y='measurement', hue='treatment', style='replicate', errorbar=('ci', 95), markers=True, dashes=False, ax=ax) ax.set_xlabel('Time (hours)') ax.set_ylabel('Measurement (AU)') sns.despine()
undefined

Multi-Panel Figures with Seaborn

Seaborn多面板图表

Using FacetGrid for automatic faceting:
python
undefined
使用FacetGrid自动分面:
python
undefined

Create faceted plot

创建分面图表

g = sns.relplot(data=df, x='dose', y='response', hue='treatment', col='cell_line', row='timepoint', kind='line', height=2.5, aspect=1.2, errorbar=('ci', 95), markers=True) g.set_axis_labels('Dose (μM)', 'Response (AU)') g.set_titles('{row_name} | {col_name}') sns.despine()
g = sns.relplot(data=df, x='dose', y='response', hue='treatment', col='cell_line', row='timepoint', kind='line', height=2.5, aspect=1.2, errorbar=('ci', 95), markers=True) g.set_axis_labels('Dose (μM)', 'Response (AU)') g.set_titles('{row_name} | {col_name}') sns.despine()

Save with correct DPI

以正确DPI保存

from figure_export import save_publication_figure save_publication_figure(g.figure, 'figure_facets', formats=['pdf', 'png'], dpi=300)

**Combining seaborn with matplotlib subplots:**
```python
from figure_export import save_publication_figure save_publication_figure(g.figure, 'figure_facets', formats=['pdf', 'png'], dpi=300)

**Seaborn与matplotlib子图结合:**
```python

Create custom multi-panel layout

创建自定义多面板布局

fig, axes = plt.subplots(2, 2, figsize=(7, 6))
fig, axes = plt.subplots(2, 2, figsize=(7, 6))

Panel A: Scatter with regression

面板A:带回归线的散点图

sns.regplot(data=df, x='predictor', y='response', ax=axes[0, 0]) axes[0, 0].text(-0.15, 1.05, 'A', transform=axes[0, 0].transAxes, fontsize=10, fontweight='bold')
sns.regplot(data=df, x='predictor', y='response', ax=axes[0, 0]) axes[0, 0].text(-0.15, 1.05, 'A', transform=axes[0, 0].transAxes, fontsize=10, fontweight='bold')

Panel B: Distribution comparison

面板B:分布对比

sns.violinplot(data=df, x='group', y='value', ax=axes[0, 1]) axes[0, 1].text(-0.15, 1.05, 'B', transform=axes[0, 1].transAxes, fontsize=10, fontweight='bold')
sns.violinplot(data=df, x='group', y='value', ax=axes[0, 1]) axes[0, 1].text(-0.15, 1.05, 'B', transform=axes[0, 1].transAxes, fontsize=10, fontweight='bold')

Panel C: Heatmap

面板C:热力图

sns.heatmap(correlation_data, cmap='viridis', ax=axes[1, 0]) axes[1, 0].text(-0.15, 1.05, 'C', transform=axes[1, 0].transAxes, fontsize=10, fontweight='bold')
sns.heatmap(correlation_data, cmap='viridis', ax=axes[1, 0]) axes[1, 0].text(-0.15, 1.05, 'C', transform=axes[1, 0].transAxes, fontsize=10, fontweight='bold')

Panel D: Time series

面板D:时间序列

sns.lineplot(data=timeseries, x='time', y='signal', hue='condition', ax=axes[1, 1]) axes[1, 1].text(-0.15, 1.05, 'D', transform=axes[1, 1].transAxes, fontsize=10, fontweight='bold')
plt.tight_layout() sns.despine()
undefined
sns.lineplot(data=timeseries, x='time', y='signal', hue='condition', ax=axes[1, 1]) axes[1, 1].text(-0.15, 1.05, 'D', transform=axes[1, 1].transAxes, fontsize=10, fontweight='bold')
plt.tight_layout() sns.despine()
undefined

Color Palettes for Publications

适用于发表的Seaborn配色方案

Seaborn includes several colorblind-safe palettes:
python
undefined
Seaborn包含多种色盲友好配色方案:
python
undefined

Use built-in colorblind palette (recommended)

使用内置色盲友好配色(推荐)

sns.set_palette('colorblind')
sns.set_palette('colorblind')

Or specify custom colorblind-safe colors (Okabe-Ito)

或指定自定义色盲友好配色(Okabe-Ito)

okabe_ito = ['#E69F00', '#56B4E9', '#009E73', '#F0E442', '#0072B2', '#D55E00', '#CC79A7', '#000000'] sns.set_palette(okabe_ito)
okabe_ito = ['#E69F00', '#56B4E9', '#009E73', '#F0E442', '#0072B2', '#D55E00', '#CC79A7', '#000000'] sns.set_palette(okabe_ito)

For heatmaps and continuous data

针对热力图和连续数据

sns.heatmap(data, cmap='viridis') # Perceptually uniform sns.heatmap(corr, cmap='RdBu_r', center=0) # Diverging, centered
undefined
sns.heatmap(data, cmap='viridis') # 感知均匀配色 sns.heatmap(corr, cmap='RdBu_r', center=0) # 发散配色,居中显示
undefined

Choosing Between Axes-Level and Figure-Level Functions

选择轴级与图级函数

Axes-level functions (e.g.,
scatterplot
,
boxplot
,
heatmap
):
  • Use when building custom multi-panel layouts
  • Accept
    ax=
    parameter for precise placement
  • Better integration with matplotlib subplots
  • More control over figure composition
python
fig, ax = plt.subplots(figsize=(3.5, 2.5))
sns.scatterplot(data=df, x='x', y='y', hue='group', ax=ax)
Figure-level functions (e.g.,
relplot
,
catplot
,
displot
):
  • Use for automatic faceting by categorical variables
  • Create complete figures with consistent styling
  • Great for exploratory analysis
  • Use
    height
    and
    aspect
    for sizing
python
g = sns.relplot(data=df, x='x', y='y', col='category', kind='scatter')
轴级函数(如
scatterplot
boxplot
heatmap
):
  • 用于构建自定义多面板布局
  • 支持
    ax=
    参数实现精确定位
  • 与matplotlib子图集成度更高
  • 对图表组合的控制更精细
python
fig, ax = plt.subplots(figsize=(3.5, 2.5))
sns.scatterplot(data=df, x='x', y='y', hue='group', ax=ax)
图级函数(如
relplot
catplot
displot
):
  • 用于按分类变量自动分面
  • 创建样式统一的完整图表
  • 非常适合探索性分析
  • 使用
    height
    aspect
    设置尺寸
python
g = sns.relplot(data=df, x='x', y='y', col='category', kind='scatter')

Statistical Rigor with Seaborn

Seaborn的统计严谨性

Seaborn automatically computes and displays uncertainty:
python
undefined
Seaborn自动计算并展示不确定性:
python
undefined

Line plot: shows mean ± 95% CI by default

折线图:默认显示均值±95%置信区间

sns.lineplot(data=df, x='time', y='value', hue='treatment', errorbar=('ci', 95)) # Can change to 'sd', 'se', etc.
sns.lineplot(data=df, x='time', y='value', hue='treatment', errorbar=('ci', 95)) # 可改为'sd'、'se'等

Bar plot: shows mean with bootstrapped CI

柱状图:显示均值与自助法置信区间

sns.barplot(data=df, x='treatment', y='response', errorbar=('ci', 95), capsize=0.1)
sns.barplot(data=df, x='treatment', y='response', errorbar=('ci', 95), capsize=0.1)

Always specify error type in figure caption:

务必在图注中说明误差类型:

"Error bars represent 95% confidence intervals"

"误差棒代表95%置信区间"

undefined
undefined

Best Practices for Publication-Ready Seaborn Figures

Seaborn期刊级图表最佳实践

  1. Always set publication theme first:
    python
    sns.set_theme(style='ticks', context='paper', font_scale=1.1)
  2. Use colorblind-safe palettes:
    python
    sns.set_palette('colorblind')
  3. Remove unnecessary elements:
    python
    sns.despine()  # Remove top and right spines
  4. Control figure size appropriately:
    python
    # Axes-level: use matplotlib figsize
    fig, ax = plt.subplots(figsize=(3.5, 2.5))
    
    # Figure-level: use height and aspect
    g = sns.relplot(..., height=3, aspect=1.2)
  5. Show individual data points when possible:
    python
    sns.boxplot(...)  # Summary statistics
    sns.stripplot(..., alpha=0.3)  # Individual points
  6. Include proper labels with units:
    python
    ax.set_xlabel('Time (hours)')
    ax.set_ylabel('Expression (AU)')
  7. Export at correct resolution:
    python
    from figure_export import save_publication_figure
    save_publication_figure(fig, 'figure_name', 
                           formats=['pdf', 'png'], dpi=300)
  1. 务必先设置发表主题:
    python
    sns.set_theme(style='ticks', context='paper', font_scale=1.1)
  2. 使用色盲友好配色方案:
    python
    sns.set_palette('colorblind')
  3. 移除不必要元素:
    python
    sns.despine()  # 移除顶部和右侧边框
  4. 合理控制图表尺寸:
    python
    # 轴级:使用matplotlib的figsize
    fig, ax = plt.subplots(figsize=(3.5, 2.5))
    
    # 图级:使用height和aspect
    g = sns.relplot(..., height=3, aspect=1.2)
  5. 尽可能展示单个数据点:
    python
    sns.boxplot(...)  # 汇总统计量
    sns.stripplot(..., alpha=0.3)  # 单个数据点
  6. 添加带单位的规范标签:
    python
    ax.set_xlabel('Time (hours)')
    ax.set_ylabel('Expression (AU)')
  7. 以正确分辨率导出:
    python
    from figure_export import save_publication_figure
    save_publication_figure(fig, 'figure_name', 
                           formats=['pdf', 'png'], dpi=300)

Advanced Seaborn Techniques

Seaborn高级技巧

Pairwise relationships for exploratory analysis:
python
undefined
探索性分析的成对关系:
python
undefined

Quick overview of all relationships

快速查看所有变量间关系

g = sns.pairplot(data=df, hue='condition', vars=['gene1', 'gene2', 'gene3'], corner=True, diag_kind='kde', height=2)

**Hierarchical clustering heatmap:**
```python
g = sns.pairplot(data=df, hue='condition', vars=['gene1', 'gene2', 'gene3'], corner=True, diag_kind='kde', height=2)

**层次聚类热力图:**
```python

Cluster samples and features

对样本和特征进行聚类

g = sns.clustermap(expression_data, method='ward', metric='euclidean', z_score=0, cmap='RdBu_r', center=0, figsize=(10, 8), row_colors=condition_colors, cbar_kws={'label': 'Z-score'})

**Joint distributions with marginals:**
```python
g = sns.clustermap(expression_data, method='ward', metric='euclidean', z_score=0, cmap='RdBu_r', center=0, figsize=(10, 8), row_colors=condition_colors, cbar_kws={'label': 'Z-score'})

**带边缘分布的联合分布:**
```python

Bivariate distribution with context

带上下文信息的双变量分布

g = sns.jointplot(data=df, x='gene1', y='gene2', hue='treatment', kind='scatter', height=6, ratio=4, marginal_kws={'kde': True})
undefined
g = sns.jointplot(data=df, x='gene1', y='gene2', hue='treatment', kind='scatter', height=6, ratio=4, marginal_kws={'kde': True})
undefined

Common Seaborn Issues and Solutions

Seaborn常见问题与解决方案

Issue: Legend outside plot area
python
g = sns.relplot(...)
g._legend.set_bbox_to_anchor((0.9, 0.5))
Issue: Overlapping labels
python
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
Issue: Text too small at final size
python
sns.set_context('paper', font_scale=1.2)  # Increase if needed
问题:图例超出图表区域
python
g = sns.relplot(...)
g._legend.set_bbox_to_anchor((0.9, 0.5))
问题:标签重叠
python
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
问题:最终尺寸下文本过小
python
sns.set_context('paper', font_scale=1.2)  # 必要时增大字号

Additional Resources

额外资源

For more detailed seaborn information, see:
  • scientific-packages/seaborn/SKILL.md
    - Comprehensive seaborn documentation
  • scientific-packages/seaborn/references/examples.md
    - Practical use cases
  • scientific-packages/seaborn/references/function_reference.md
    - Complete API reference
  • scientific-packages/seaborn/references/objects_interface.md
    - Modern declarative API
如需更详细的Seaborn信息,请查看:
  • scientific-packages/seaborn/SKILL.md
    :Seaborn完整文档
  • scientific-packages/seaborn/references/examples.md
    :实用案例
  • scientific-packages/seaborn/references/function_reference.md
    :完整API参考
  • scientific-packages/seaborn/references/objects_interface.md
    :现代声明式API

Plotly

Plotly

  • Interactive figures for exploration
  • Export static images for publication
  • Configure for publication quality:
python
fig.update_layout(
    font=dict(family='Arial, sans-serif', size=10),
    plot_bgcolor='white',
    # ... see matplotlib_examples.md Example 8
)
fig.write_image('figure.png', scale=3)  # scale=3 gives ~300 DPI
  • 用于探索分析的交互式图表
  • 可导出静态图像用于发表
  • 配置为期刊级质量:
python
fig.update_layout(
    font=dict(family='Arial, sans-serif', size=10),
    plot_bgcolor='white',
    # ... 详见matplotlib_examples.md示例8
)
fig.write_image('figure.png', scale=3)  # scale=3对应约300 DPI

Resources

资源

References Directory

参考文档目录

Load these as needed for detailed information:
  • publication_guidelines.md
    : Comprehensive best practices
    • Resolution and file format requirements
    • Typography guidelines
    • Layout and composition rules
    • Statistical rigor requirements
    • Complete publication checklist
  • color_palettes.md
    : Color usage guide
    • Colorblind-friendly palette specifications with RGB values
    • Sequential and diverging colormap recommendations
    • Testing procedures for accessibility
    • Domain-specific palettes (genomics, microscopy)
  • journal_requirements.md
    : Journal-specific specifications
    • Technical requirements by publisher
    • File format and DPI specifications
    • Figure dimension requirements
    • Quick reference table
  • matplotlib_examples.md
    : Practical code examples
    • 10 complete working examples
    • Line plots, bar plots, heatmaps, multi-panel figures
    • Journal-specific figure examples
    • Tips for each library (matplotlib, seaborn, plotly)
按需查阅获取详细信息:
  • publication_guidelines.md
    :全面的最佳实践指南
    • 分辨率与文件格式要求
    • 排版指南
    • 布局与构图规则
    • 统计严谨性要求
    • 完整发表检查清单
  • color_palettes.md
    :颜色使用指南
    • 色盲友好配色方案的RGB值规范
    • 顺序型与发散型颜色映射推荐
    • 可访问性测试流程
    • 领域专属配色(基因组学、显微学)
  • journal_requirements.md
    :期刊专属规范
    • 各出版商的技术要求
    • 文件格式与DPI规范
    • 图表尺寸要求
    • 快速参考表格
  • matplotlib_examples.md
    :实用代码示例
    • 10个完整可运行示例
    • 折线图、柱状图、热力图、多面板图表
    • 期刊专属图表示例
    • 各库(matplotlib、seaborn、plotly)使用技巧

Scripts Directory

脚本目录

Use these helper scripts for automation:
  • figure_export.py
    : Export utilities
    • save_publication_figure()
      : Save in multiple formats with correct DPI
    • save_for_journal()
      : Use journal-specific requirements automatically
    • check_figure_size()
      : Verify dimensions meet journal specs
    • Run directly:
      python scripts/figure_export.py
      for examples
  • style_presets.py
    : Pre-configured styles
    • apply_publication_style()
      : Apply preset styles (default, nature, science, cell)
    • set_color_palette()
      : Quick palette switching
    • configure_for_journal()
      : One-command journal configuration
    • Run directly:
      python scripts/style_presets.py
      to see examples
使用这些辅助脚本实现自动化:
  • figure_export.py
    :导出工具
    • save_publication_figure()
      :以正确DPI保存为多种格式
    • save_for_journal()
      :自动应用期刊专属要求
    • check_figure_size()
      :验证尺寸是否符合期刊规范
    • 直接运行:
      python scripts/figure_export.py
      查看示例
  • style_presets.py
    :预配置样式
    • apply_publication_style()
      :应用预设样式(默认、nature、science、cell)
    • set_color_palette()
      :快速切换配色方案
    • configure_for_journal()
      :一键配置期刊规范
    • 直接运行:
      python scripts/style_presets.py
      查看示例

Assets Directory

资源文件目录

Use these files in figures:
  • color_palettes.py
    : Importable color definitions
    • All recommended palettes as Python constants
    • apply_palette()
      helper function
    • Can be imported directly into notebooks/scripts
  • Matplotlib style files: Use with
    plt.style.use()
    • publication.mplstyle
      : General publication quality
    • nature.mplstyle
      : Nature journal specifications
    • presentation.mplstyle
      : Larger fonts for posters/slides
在图表中使用这些文件:
  • color_palettes.py
    :可导入的颜色定义
    • 所有推荐配色方案的Python常量
    • apply_palette()
      辅助函数
    • 可直接导入到笔记本/脚本中
  • Matplotlib样式文件:配合
    plt.style.use()
    使用
    • publication.mplstyle
      :通用发表级样式
    • nature.mplstyle
      :《自然》期刊规范
    • presentation.mplstyle
      :适用于海报/幻灯片的大字体样式

Workflow Summary

工作流程总结

Recommended workflow for creating publication figures:
  1. Plan: Determine target journal, figure type, and content
  2. Configure: Apply appropriate style for journal
    python
    from style_presets import configure_for_journal
    configure_for_journal('nature', 'single')
  3. Create: Build figure with proper labels, colors, statistics
  4. Verify: Check size, fonts, colors, accessibility
    python
    from figure_export import check_figure_size
    check_figure_size(fig, journal='nature')
  5. Export: Save in required formats
    python
    from figure_export import save_for_journal
    save_for_journal(fig, 'figure1', 'nature', 'combination')
  6. Review: View at final size in manuscript context
创建发表级图表的推荐工作流程:
  1. 规划:确定目标期刊、图表类型与内容
  2. 配置:应用对应期刊的样式
    python
    from style_presets import configure_for_journal
    configure_for_journal('nature', 'single')
  3. 创建:构建包含规范标签、配色、统计信息的图表
  4. 验证:检查尺寸、字体、配色、可访问性
    python
    from figure_export import check_figure_size
    check_figure_size(fig, journal='nature')
  5. 导出:保存为所需格式
    python
    from figure_export import save_for_journal
    save_for_journal(fig, 'figure1', 'nature', 'combination')
  6. 审核:在稿件语境下查看最终尺寸的图表

Common Pitfalls to Avoid

需避免的常见陷阱

  1. Font too small: Text unreadable when printed at final size
  2. JPEG format: Never use JPEG for graphs/plots (creates artifacts)
  3. Red-green colors: ~8% of males cannot distinguish
  4. Low resolution: Pixelated figures in publication
  5. Missing units: Always label axes with units
  6. 3D effects: Distorts perception, avoid completely
  7. Chart junk: Remove unnecessary gridlines, decorations
  8. Truncated axes: Start bar charts at zero unless scientifically justified
  9. Inconsistent styling: Different fonts/colors across figures in same manuscript
  10. No error bars: Always show uncertainty
  1. 字体过小:最终打印时文本无法辨认
  2. 使用JPEG格式:绝对不要用JPEG保存统计图/曲线图(会产生失真)
  3. 红绿色配色:约8%的男性无法区分
  4. 分辨率过低:发表时图表出现像素化
  5. 缺少单位:务必为坐标轴标注单位
  6. 3D效果:会扭曲视觉感知,完全避免使用
  7. 冗余元素:删除不必要的网格线、装饰
  8. 坐标轴截断:柱状图务必从0开始,除非有科学依据
  9. 样式不一致:同一稿件中不同图表的字体/配色不统一
  10. 无误差棒:务必展示数据不确定性

Final Checklist

最终检查清单

Before submitting figures, verify:
  • Resolution meets journal requirements (300+ DPI)
  • File format is correct (vector for plots, TIFF for images)
  • Figure size matches journal specifications
  • All text readable at final size (≥6 pt)
  • Colors are colorblind-friendly
  • Figure works in grayscale
  • All axes labeled with units
  • Error bars present with definition in caption
  • Panel labels present and consistent
  • No chart junk or 3D effects
  • Fonts consistent across all figures
  • Statistical significance clearly marked
  • Legend is clear and complete
Use this skill to ensure scientific figures meet the highest publication standards while remaining accessible to all readers.
提交图表前,请验证:
  • 分辨率符合期刊要求(300+ DPI)
  • 文件格式正确(图表用矢量格式,图像用TIFF)
  • 图表尺寸匹配期刊规范
  • 所有文本在最终尺寸下可读(≥6 pt)
  • 配色为色盲友好型
  • 图表在灰度模式下可解读
  • 所有坐标轴均标注单位
  • 包含误差棒,并在图注中说明类型
  • 面板标签完整且统一
  • 无冗余元素或3D效果
  • 所有图表字体统一
  • 统计显著性标记清晰
  • 图例清晰完整
使用本技能确保科学图表达到最高发表标准,同时对所有读者具备可访问性。