scientific-visualization
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseScientific 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
在以下场景中应使用该技能:
- 为科学手稿创建图表或可视化内容
- 准备用于期刊投稿的图表(如Nature、Science、Cell、PLOS等)
- 确保图表对色盲人群友好且具有可访问性
- 创建具有一致样式的多面板图表
- 以正确的分辨率和格式导出图表
- 遵循特定的期刊发表指南
- 改进现有图表使其达到发表标准
- 创建可同时在彩色和灰度模式下正常展示的图表
Quick Start Guide
快速入门指南
Basic Publication-Quality Figure
基础可发表质量图表
python
import matplotlib.pyplot as plt
import numpy as nppython
import matplotlib.pyplot as plt
import numpy as npApply 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('时间(秒)')
ax.set_ylabel('振幅(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)
undefinedfrom figure_export import save_publication_figure
save_publication_figure(fig, 'figure1', formats=['pdf', 'png'], dpi=300)
undefinedUsing Pre-configured Styles
使用预配置样式
Apply journal-specific styles using the matplotlib style files in :
assets/python
import matplotlib.pyplot as plt使用目录中的matplotlib样式文件应用期刊特定样式:
assets/python
import matplotlib.pyplot as pltOption 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
现在创建图表 - 它们将自动匹配Nature的规范
fig, ax = plt.subplots()
fig, ax = plt.subplots()
... your plotting code ...
... 你的绘图代码 ...
undefinedundefinedQuick 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_styleApply 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('响应值(μM)')
sns.despine()
Save figure
保存图表
from figure_export import save_publication_figure
save_publication_figure(fig, 'treatment_comparison', formats=['pdf', 'png'], dpi=300)
undefinedfrom figure_export import save_publication_figure
save_publication_figure(fig, 'treatment_comparison', formats=['pdf', 'png'], dpi=300)
undefinedCore 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
undefinedUse 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')
undefinedfrom figure_export import save_for_journal
save_for_journal(fig, 'figure1', journal='nature', figure_type='combination')
undefined2. Color Selection - Colorblind Accessibility
2. 颜色选择 - 色盲可访问性
Always use colorblind-friendly palettes (detailed in ):
references/color_palettes.mdRecommended: Okabe-Ito palette (distinguishable by all types of color blindness):
python
undefined始终使用色盲友好的配色方案(详情见):
references/color_palettes.md推荐:Okabe-Ito配色方案(所有类型色盲人群均可区分):
python
undefinedOption 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磅
- 刻度标签:6-8磅
- 面板标签:8-12磅(加粗)
- 标签采用句首大写格式:"时间(小时)"而非"TIME(HOURS)"
- 始终在括号中包含单位
实现方式:
python
undefinedSet 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
undefinedimport 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
undefined4. 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- Nature:单栏89毫米,双栏183毫米
- Science:单栏55毫米,双栏175毫米
- Cell:单栏85毫米,双栏178毫米
检查图表尺寸合规性:
python
from figure_export import check_figure_size
fig = plt.figure(figsize=(3.5, 3)) # Nature的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 for complete code):
references/matplotlib_examples.mdpython
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])最佳实践:
- 使用加粗字母标记面板:A、B、C(大多数期刊用大写,Nature用小写)
- 所有面板保持一致的样式
- 尽可能对齐面板边缘
- 面板间保留足够的空白
示例实现(完整代码见):
references/matplotlib_examples.mdpython
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')
undefinedfor i, ax in enumerate([ax1, ax2, ...]):
ax.text(-0.15, 1.05, ascii_uppercase[i], transform=ax.transAxes,
fontsize=10, fontweight='bold', va='top')
undefinedCommon Tasks
常见任务
Task 1: Create a Publication-Ready Line Plot
任务1:创建可发表的折线图
See Example 1 for complete code.
references/matplotlib_examples.mdKey steps:
- Apply publication style
- Set appropriate figure size for target journal
- Use colorblind-friendly colors
- Add error bars with correct representation (SEM, SD, or CI)
- Label axes with units
- Remove unnecessary spines
- 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()完整代码见示例1。
references/matplotlib_examples.md关键步骤:
- 应用发表样式
- 为目标期刊设置合适的图表尺寸
- 使用色盲友好的颜色
- 添加正确表示的误差棒(标准误、标准差或置信区间)
- 为坐标轴添加带单位的标签
- 移除不必要的边框
- 保存为矢量格式
使用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('时间(小时)')
ax.set_ylabel('测量值(AU)')
sns.despine()Task 2: Create a Multi-Panel Figure
任务2:创建多面板图表
See Example 2 for complete code.
references/matplotlib_examples.mdKey steps:
- Use for flexible layout
GridSpec - Ensure consistent styling across panels
- Add bold panel labels (A, B, C, etc.)
- Align related panels
- Verify all text is readable at final size
完整代码见示例2。
references/matplotlib_examples.md关键步骤:
- 使用实现灵活布局
GridSpec - 确保所有面板样式一致
- 添加加粗的面板标签(A、B、C等)
- 对齐相关面板
- 验证所有文本在最终尺寸下可读
Task 3: Create a Heatmap with Proper Colormap
任务3:创建带合适颜色映射的热图
See Example 4 for complete code.
references/matplotlib_examples.mdKey steps:
- Use perceptually uniform colormap (,
viridis,plasma)cividis - Include labeled colorbar
- For diverging data, use colorblind-safe diverging map (,
RdBu_r)PuOr - Set appropriate center value for diverging maps
- 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)完整代码见示例4。
references/matplotlib_examples.md关键步骤:
- 使用感知均匀的颜色映射(、
viridis、plasma)cividis - 包含带标签的颜色条
- 对于发散数据,使用色盲友好的发散映射(、
RdBu_r)PuOr - 为发散映射设置合适的中心值
- 在灰度模式下测试显示效果
使用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:
- Check journal requirements:
references/journal_requirements.md - Configure matplotlib for journal:
python
from style_presets import configure_for_journal configure_for_journal('nature', figure_width='single') - Create figure (will auto-size correctly)
- Export with journal specifications:
python
from figure_export import save_for_journal save_for_journal(fig, 'figure1', journal='nature', figure_type='line_art')
工作流程:
- 查看期刊要求:
references/journal_requirements.md - 为期刊配置matplotlib:
python
from style_presets import configure_for_journal configure_for_journal('nature', figure_width='single') - 创建图表(将自动调整为正确尺寸)
- 按期刊规范导出:
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- Check resolution: Verify DPI meets journal requirements
- Check file format: Use vector for plots, TIFF/PNG for images
- Check colors: Ensure colorblind-friendly
- Check fonts: Minimum 6-7 pt at final size, sans-serif
- Check labels: All axes labeled with units
- Check size: Matches journal column width
- Test grayscale: Figure interpretable without color
- Remove chart junk: No unnecessary grids, 3D effects, shadows
清单法(完整清单见):
references/publication_guidelines.md- 检查分辨率:验证DPI符合期刊要求
- 检查文件格式:图表使用矢量格式,图像使用TIFF/PNG
- 检查颜色:确保色盲友好
- 检查字体:最终尺寸下最小6-7磅,使用无衬线字体
- 检查标签:所有坐标轴均带单位标签
- 检查尺寸:匹配期刊栏宽
- 灰度测试:图表在无颜色时仍可解释
- 移除冗余元素:移除不必要的网格、3D效果、阴影
Task 6: Create Colorblind-Friendly Visualizations
任务6:创建色盲友好的可视化内容
Strategy:
- Use approved palettes from
assets/color_palettes.py - Add redundant encoding (line styles, markers, patterns)
- Test with colorblind simulator
- Ensure grayscale compatibility
Example:
python
from color_palettes import apply_palette
import matplotlib.pyplot as plt
apply_palette('okabe_ito')策略:
- 使用中的已批准配色方案
assets/color_palettes.py - 添加冗余编码(线型、标记、图案)
- 使用色盲模拟器测试
- 确保灰度兼容性
示例:
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)
undefinedline_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)
undefinedStatistical 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
undefinedShow 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)
undefinedax.text(1.5, max_y * 1.1, '***', ha='center', fontsize=8)
undefinedWorking 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 for extensive examples
references/matplotlib_examples.md
- 对发表细节的控制程度最高
- 最适合复杂的多面板图表
- 使用提供的样式文件保持格式一致
- 详细示例见
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 DataFrame的数据集导向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_styleApply 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
undefinedfig, ax = plt.subplots(figsize=(3.5, 2.5))
sns.scatterplot(data=df, x='time', y='response',
hue='treatment', style='condition', ax=ax)
sns.despine() # 移除顶部和右侧边框
undefinedCommon Plot Types for Publications
适用于发表的常见图表类型
Statistical comparisons:
python
undefined统计对比:
python
undefinedBox 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:**
```pythonfig, 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('响应值(μM)')
sns.despine()
**分布分析:**
```pythonViolin 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:**
```pythonfig, 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('基因表达量(AU)')
sns.despine()
**相关矩阵:**
```pythonHeatmap 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:**
```pythonfig, 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()
**带置信带的时间序列:**
```pythonLine 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()
undefinedfig, 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('时间(小时)')
ax.set_ylabel('测量值(AU)')
sns.despine()
undefinedMulti-Panel Figures with Seaborn
使用Seaborn创建多面板图表
Using FacetGrid for automatic faceting:
python
undefined使用FacetGrid自动分面:
python
undefinedCreate 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('剂量(μM)', '响应值(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:**
```pythonfrom figure_export import save_publication_figure
save_publication_figure(g.figure, 'figure_facets',
formats=['pdf', 'png'], dpi=300)
**结合Seaborn与matplotlib子图:**
```pythonCreate 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()
undefinedsns.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()
undefinedColor Palettes for Publications
适用于发表的Seaborn配色方案
Seaborn includes several colorblind-safe palettes:
python
undefinedSeaborn包含多种色盲友好的配色方案:
python
undefinedUse 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
undefinedsns.heatmap(data, cmap='viridis') # 感知均匀
sns.heatmap(corr, cmap='RdBu_r', center=0) # 发散型,居中
undefinedChoosing Between Axes-Level and Figure-Level Functions
选择轴级与图级函数
Axes-level functions (e.g., , , ):
scatterplotboxplotheatmap- Use when building custom multi-panel layouts
- Accept parameter for precise placement
ax= - 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., , , ):
relplotcatplotdisplot- Use for automatic faceting by categorical variables
- Create complete figures with consistent styling
- Great for exploratory analysis
- Use and
heightfor sizingaspect
python
g = sns.relplot(data=df, x='x', y='y', col='category', kind='scatter')轴级函数(如、、):
scatterplotboxplotheatmap- 构建自定义多面板布局时使用
- 接受参数进行精确定位
ax= - 与matplotlib子图更好集成
- 对图表组合有更多控制
python
fig, ax = plt.subplots(figsize=(3.5, 2.5))
sns.scatterplot(data=df, x='x', y='y', hue='group', ax=ax)图级函数(如、、):
relplotcatplotdisplot- 按分类变量自动分面时使用
- 创建样式一致的完整图表
- 非常适合探索性分析
- 使用和
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
undefinedSeaborn自动计算并展示不确定性:
python
undefinedLine 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%置信区间"
undefinedundefinedBest Practices for Publication-Ready Seaborn Figures
可发表Seaborn图表的最佳实践
-
Always set publication theme first:python
sns.set_theme(style='ticks', context='paper', font_scale=1.1) -
Use colorblind-safe palettes:python
sns.set_palette('colorblind') -
Remove unnecessary elements:python
sns.despine() # Remove top and right spines -
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) -
Show individual data points when possible:python
sns.boxplot(...) # Summary statistics sns.stripplot(..., alpha=0.3) # Individual points -
Include proper labels with units:python
ax.set_xlabel('Time (hours)') ax.set_ylabel('Expression (AU)') -
Export at correct resolution:python
from figure_export import save_publication_figure save_publication_figure(fig, 'figure_name', formats=['pdf', 'png'], dpi=300)
-
始终先设置发表主题:python
sns.set_theme(style='ticks', context='paper', font_scale=1.1) -
使用色盲友好的配色方案:python
sns.set_palette('colorblind') -
移除不必要的元素:python
sns.despine() # 移除顶部和右侧边框 -
适当控制图表尺寸:python
# 轴级:使用matplotlib的figsize fig, ax = plt.subplots(figsize=(3.5, 2.5)) # 图级:使用height和aspect g = sns.relplot(..., height=3, aspect=1.2) -
尽可能展示单个数据点:python
sns.boxplot(...) # 汇总统计 sns.stripplot(..., alpha=0.3) # 单个数据点 -
添加带单位的规范标签:python
ax.set_xlabel('时间(小时)') ax.set_ylabel('表达量(AU)') -
以正确分辨率导出: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
undefinedQuick 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:**
```pythong = sns.pairplot(data=df, hue='condition',
vars=['gene1', 'gene2', 'gene3'],
corner=True, diag_kind='kde', height=2)
**层次聚类热图:**
```pythonCluster 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:**
```pythong = 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值'})
**带边缘分布的联合分布:**
```pythonBivariate distribution with context
带上下文的双变量分布
g = sns.jointplot(data=df, x='gene1', y='gene2',
hue='treatment', kind='scatter',
height=6, ratio=4, marginal_kws={'kde': True})
undefinedg = sns.jointplot(data=df, x='gene1', y='gene2',
hue='treatment', kind='scatter',
height=6, ratio=4, marginal_kws={'kde': True})
undefinedCommon 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:
- - Comprehensive seaborn documentation
scientific-packages/seaborn/SKILL.md - - Practical use cases
scientific-packages/seaborn/references/examples.md - - Complete API reference
scientific-packages/seaborn/references/function_reference.md - - Modern declarative API
scientific-packages/seaborn/references/objects_interface.md
如需更详细的Seaborn信息,请参阅:
- - 完整Seaborn文档
scientific-packages/seaborn/SKILL.md - - 实际用例
scientific-packages/seaborn/references/examples.md - - 完整API参考
scientific-packages/seaborn/references/function_reference.md - - 现代声明式API
scientific-packages/seaborn/references/objects_interface.md
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 DPIResources
资源
References Directory
参考文档目录
Load these as needed for detailed information:
-
: Comprehensive best practices
publication_guidelines.md- Resolution and file format requirements
- Typography guidelines
- Layout and composition rules
- Statistical rigor requirements
- Complete publication checklist
-
: Color usage guide
color_palettes.md- Colorblind-friendly palette specifications with RGB values
- Sequential and diverging colormap recommendations
- Testing procedures for accessibility
- Domain-specific palettes (genomics, microscopy)
-
: Journal-specific specifications
journal_requirements.md- Technical requirements by publisher
- File format and DPI specifications
- Figure dimension requirements
- Quick reference table
-
: Practical code examples
matplotlib_examples.md- 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:
-
: Export utilities
figure_export.py- : Save in multiple formats with correct DPI
save_publication_figure() - : Use journal-specific requirements automatically
save_for_journal() - : Verify dimensions meet journal specs
check_figure_size() - Run directly: for examples
python scripts/figure_export.py
-
: Pre-configured styles
style_presets.py- : Apply preset styles (default, nature, science, cell)
apply_publication_style() - : Quick palette switching
set_color_palette() - : One-command journal configuration
configure_for_journal() - Run directly: to see examples
python scripts/style_presets.py
使用这些辅助脚本实现自动化:
-
:导出工具
figure_export.py- :以正确DPI保存为多种格式
save_publication_figure() - :自动使用期刊特定要求
save_for_journal() - :验证尺寸是否符合期刊规范
check_figure_size() - 直接运行:查看示例
python scripts/figure_export.py
-
:预配置样式
style_presets.py- :应用预设样式(默认、Nature、Science、Cell)
apply_publication_style() - :快速切换配色方案
set_color_palette() - :一键配置期刊样式
configure_for_journal() - 直接运行:查看示例
python scripts/style_presets.py
Assets Directory
资源文件目录
Use these files in figures:
-
: Importable color definitions
color_palettes.py- All recommended palettes as Python constants
- helper function
apply_palette() - Can be imported directly into notebooks/scripts
-
Matplotlib style files: Use with
plt.style.use()- : General publication quality
publication.mplstyle - : Nature journal specifications
nature.mplstyle - : Larger fonts for posters/slides
presentation.mplstyle
在图表中使用这些文件:
-
:可导入的颜色定义
color_palettes.py- 所有推荐配色方案的Python常量
- 辅助函数
apply_palette() - 可直接导入到笔记本/脚本中
-
Matplotlib样式文件:与配合使用
plt.style.use()- :通用发表质量样式
publication.mplstyle - :Nature期刊规范
nature.mplstyle - :用于海报/幻灯片的大字体样式
presentation.mplstyle
Workflow Summary
工作流程总结
Recommended workflow for creating publication figures:
- Plan: Determine target journal, figure type, and content
- Configure: Apply appropriate style for journal
python
from style_presets import configure_for_journal configure_for_journal('nature', 'single') - Create: Build figure with proper labels, colors, statistics
- Verify: Check size, fonts, colors, accessibility
python
from figure_export import check_figure_size check_figure_size(fig, journal='nature') - Export: Save in required formats
python
from figure_export import save_for_journal save_for_journal(fig, 'figure1', 'nature', 'combination') - Review: View at final size in manuscript context
创建发表图表的推荐工作流程:
- 规划:确定目标期刊、图表类型和内容
- 配置:为期刊应用合适的样式
python
from style_presets import configure_for_journal configure_for_journal('nature', 'single') - 创建:构建带正确标签、颜色和统计信息的图表
- 验证:检查尺寸、字体、颜色、可访问性
python
from figure_export import check_figure_size check_figure_size(fig, journal='nature') - 导出:保存为所需格式
python
from figure_export import save_for_journal save_for_journal(fig, 'figure1', 'nature', 'combination') - 审核:在手稿语境下以最终尺寸查看图表
Common Pitfalls to Avoid
需避免的常见陷阱
- Font too small: Text unreadable when printed at final size
- JPEG format: Never use JPEG for graphs/plots (creates artifacts)
- Red-green colors: ~8% of males cannot distinguish
- Low resolution: Pixelated figures in publication
- Missing units: Always label axes with units
- 3D effects: Distorts perception, avoid completely
- Chart junk: Remove unnecessary gridlines, decorations
- Truncated axes: Start bar charts at zero unless scientifically justified
- Inconsistent styling: Different fonts/colors across figures in same manuscript
- No error bars: Always show uncertainty
- 字体过小:最终打印时文本无法读取
- JPEG格式:绝对不要将JPEG用于图表/曲线图(会产生伪影)
- 红绿配色:约8%的男性无法区分
- 低分辨率:发表时图表出现像素化
- 缺少单位:始终为坐标轴添加单位
- 3D效果:扭曲感知,完全避免使用
- 冗余元素:移除不必要的网格线、装饰
- 坐标轴截断:除非有科学依据,否则柱状图从0开始
- 样式不一致:同一手稿中不同图表的字体/颜色不一致
- 无误差棒:始终展示不确定性
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磅)
- 颜色对色盲人群友好
- 图表在灰度模式下可正常展示
- 所有坐标轴均带单位标签
- 包含误差棒,并在图注中说明类型
- 面板标签存在且样式一致
- 无冗余元素或3D效果
- 所有图表字体一致
- 统计显著性标记清晰
- 图例清晰完整
使用本技能确保科学图表达到最高发表标准,同时对所有读者保持可访问性。