24 KiB
name, description, license, metadata
| name | description | license | metadata | ||||
|---|---|---|---|---|---|---|---|
| scientific-visualization | 用于制作达到发表质量图形的元技能。在需要创建期刊投稿图形时使用,要求包含多面板布局、显著性标注、误差线、色盲友好调色板以及特定期刊(Nature、Science、Cell)格式。使用 matplotlib/seaborn/plotly 配合发表样式进行编排。快速探索请直接使用 seaborn 或 plotly。 | MIT license |
|
Scientific Visualization
概述
科学可视化将数据转换为清晰、准确的发表级图形。创建具有多面板布局、误差线、显著性标记和色盲友好调色板的期刊就绪图表。使用 matplotlib、seaborn 和 plotly 导出为 PDF/EPS/TIFF 格式,用于学术手稿。
何时使用本技能
以下情况应使用本技能:
- 为科学手稿创建图形或可视化
- 为期刊投稿准备图表(Nature、Science、Cell、PLOS 等)
- 确保图形色盲友好且无障碍可读
- 制作风格一致的多面板图形
- 以正确的分辨率和格式导出图形
- 遵循特定的出版指南
- 改进现有图形以符合发表标准
- 创建需在彩色和灰度下均能清晰显示的图形
快速入门指南
基本发表质量图形
import matplotlib.pyplot as plt
import numpy as np
# 应用发表样式(来自 scripts/style_presets.py)
from style_presets import apply_publication_style
apply_publication_style('default')
# 创建合适尺寸的图形(单栏 = 3.5 英寸)
fig, ax = plt.subplots(figsize=(3.5, 2.5))
# 绘制数据
x = np.linspace(0, 10, 100)
ax.plot(x, np.sin(x), label='sin(x)')
ax.plot(x, np.cos(x), label='cos(x)')
# 正确标注单位
ax.set_xlabel('Time (seconds)')
ax.set_ylabel('Amplitude (mV)')
ax.legend(frameon=False)
# 移除不必要的边框
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
# 以发表格式保存(来自 figure_export.py)
from figure_export import save_publication_figure
save_publication_figure(fig, 'figure1', formats=['pdf', 'png'], dpi=300)
使用预配置样式
使用 assets/ 中的 matplotlib 样式文件应用特定期刊样式:
import matplotlib.pyplot as plt
# 选项 1:直接使用样式文件
plt.style.use('assets/nature.mplstyle')
# 选项 2:使用 style_presets.py 辅助函数
from style_presets import configure_for_journal
configure_for_journal('nature', figure_width='single')
# 现在创建图形——它们将自动符合 Nature 规格
fig, ax = plt.subplots()
# ... 你的绘图代码 ...
使用 Seaborn 快速入门
对于统计图形,使用 seaborn 配合发表样式:
import seaborn as sns
import matplotlib.pyplot as plt
from style_presets import apply_publication_style
# 应用发表样式
apply_publication_style('default')
sns.set_theme(style='ticks', context='paper', font_scale=1.1)
sns.set_palette('colorblind')
# 创建统计比较图
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()
# 保存图形
from figure_export import save_publication_figure
save_publication_figure(fig, 'treatment_comparison', formats=['pdf', 'png'], dpi=300)
核心原则与最佳实践
1. 分辨率与文件格式
关键要求(详见 references/publication_guidelines.md):
- 栅格图像(照片、显微镜):300-600 DPI
- 线条图(图表、曲线图):600-1200 DPI 或矢量格式
- 矢量格式(首选):PDF、EPS、SVG
- 栅格格式:TIFF、PNG(科学数据切勿使用 JPEG)
实现方式:
# 使用 figure_export.py 脚本设置正确参数
from figure_export import save_publication_figure
# 以多种格式保存,DPI 正确
save_publication_figure(fig, 'myfigure', formats=['pdf', 'png'], dpi=300)
# 或按特定期刊要求保存
from figure_export import save_for_journal
save_for_journal(fig, 'figure1', journal='nature', figure_type='combination')
2. 颜色选择——色盲无障碍
始终使用色盲友好调色板(详见 references/color_palettes.md):
推荐:Okabe-Ito 调色板(所有类型的色盲均可区分):
# 选项 1:使用 assets/color_palettes.py
from color_palettes import OKABE_ITO_LIST, apply_palette
apply_palette('okabe_ito')
# 选项 2:手动指定
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. 字体与文本
字体指南(详见 references/publication_guidelines.md):
- 无衬线字体:Arial、Helvetica、Calibri
- 最终印刷尺寸下的最小字号:
- 轴标签:7-9 pt
- 刻度标签:6-8 pt
- 面板标签:8-12 pt(粗体)
- 标签使用句首大写:写 "Time (hours)" 而非 "TIME (HOURS)"
- 始终在括号内包含单位
实现方式:
# 全局设置字体
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
4. 图形尺寸
期刊特定宽度(详见 references/journal_requirements.md):
- Nature:单栏 89 mm,双栏 183 mm
- Science:单栏 55 mm,双栏 175 mm
- Cell:单栏 85 mm,双栏 178 mm
检查图形尺寸合规性:
from figure_export import check_figure_size
fig = plt.figure(figsize=(3.5, 3)) # Nature 的 89 mm
check_figure_size(fig, journal='nature')
5. 多面板图形
最佳实践:
- 使用粗体字母标注面板:A、B、C(大多数期刊用大写,Nature 用小写)
- 所有面板保持风格一致
- 尽可能沿边缘对齐面板
- 面板之间保留适当的空白
示例实现(完整代码见 references/matplotlib_examples.md):
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])
# ... 创建其他面板 ...
# 添加面板标签
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')
常见任务
任务 1:创建可用于发表的线图
完整代码见 references/matplotlib_examples.md 示例 1。
关键步骤:
- 应用发表样式
- 为目标期刊设置合适的图形尺寸
- 使用色盲友好颜色
- 添加正确表示的误差线(SEM、SD 或 CI)
- 标注轴及单位
- 移除不必要的边框
- 以矢量格式保存
使用 seaborn 自动计算置信区间:
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()
任务 2:创建多面板图形
完整代码见 references/matplotlib_examples.md 示例 2。
关键步骤:
- 使用
GridSpec实现灵活布局 - 确保所有面板风格一致
- 添加粗体面板标签(A、B、C 等)
- 对齐相关面板
- 验证所有文本在最终尺寸下可读
任务 3:创建使用正确颜色映射的热力图
完整代码见 references/matplotlib_examples.md 示例 4。
关键步骤:
- 使用感知均匀的颜色映射(
viridis、plasma、cividis) - 包含带标注的颜色条
- 对于发散型数据,使用色盲安全的发散映射(
RdBu_r、PuOr) - 为发散映射设置合适的中心值
- 测试灰度显示效果
使用 seaborn 绘制相关矩阵:
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/journal_requirements.md - 为期刊配置 matplotlib:
from style_presets import configure_for_journal configure_for_journal('nature', figure_width='single') - 创建图形(将自动调整尺寸)
- 按期刊规格导出:
from figure_export import save_for_journal save_for_journal(fig, 'figure1', journal='nature', figure_type='line_art')
任务 5:修复现有图形使其符合发表标准
清单式方法(完整清单见 references/publication_guidelines.md):
- 检查分辨率:确认 DPI 符合期刊要求
- 检查文件格式:图形用矢量格式,图像用 TIFF/PNG
- 检查颜色:确保色盲友好
- 检查字体:最终尺寸下最小 6-7 pt,无衬线字体
- 检查标签:所有轴标注单位
- 检查尺寸:匹配期刊栏宽
- 测试灰度:无颜色也能解读图形
- 去除图表垃圾:不要不必要的网格、3D 效果、阴影
任务 6:创建色盲友好的可视化
策略:
- 使用
assets/color_palettes.py中的认可调色板 - 添加冗余编码(线型、标记、图案)
- 使用色盲模拟器测试
- 确保灰度兼容
示例:
from color_palettes import apply_palette
import matplotlib.pyplot as plt
apply_palette('okabe_ito')
# 在颜色之外添加冗余编码
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)
统计严谨性
始终包含:
- 误差线(SD、SEM 或 CI——在说明中注明具体类型)
- 样本量(n)在图中或说明中
- 统计显著性标记(、、)
- 尽可能显示个体数据点(而不仅仅是汇总统计量)
含统计信息的示例:
# 显示个体数据点及汇总统计量
ax.scatter(x_jittered, individual_points, alpha=0.4, s=8)
ax.errorbar(x, means, yerr=sems, fmt='o', capsize=3)
# 标记显著性
ax.text(1.5, max_y * 1.1, '***', ha='center', fontsize=8)
使用不同的绘图库
Matplotlib
- 对发表细节的控制最全面
- 最适合复杂的多面板图形
- 使用提供的样式文件实现统一格式
- 更多示例见
references/matplotlib_examples.md
Seaborn
Seaborn 提供了一种高级的、面向数据集的统计图形接口,构建于 matplotlib 之上。它在使用最少代码创建发表质量的统计可视化方面表现出色,同时与 matplotlib 自定义功能完全兼容。
科学可视化的主要优势:
- 自动统计估计和置信区间
- 内置多面板图形支持(分面)
- 默认使用色盲友好调色板
- 基于 pandas DataFrame 的面向数据集 API
- 变量到视觉属性的语义映射
发表样式快速入门
始终先应用 matplotlib 发表样式,然后配置 seaborn:
import seaborn as sns
import matplotlib.pyplot as plt
from style_presets import apply_publication_style
# 应用发表样式
apply_publication_style('default')
# 为发表配置 seaborn
sns.set_theme(style='ticks', context='paper', font_scale=1.1)
sns.set_palette('colorblind') # 使用色盲安全调色板
# 创建图形
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() # 移除顶部和右侧边框
用于发表的常见图形类型
统计比较:
# 带个体数据点的箱线图,增加透明度
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=(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()
相关矩阵:
# 使用正确颜色映射和标注的热力图
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()
带置信带的时序图:
# 自动计算置信区间的线图
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()
使用 Seaborn 创建多面板图形
使用 FacetGrid 自动分面:
# 创建分面图
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()
# 以正确 DPI 保存
from figure_export import save_publication_figure
save_publication_figure(g.figure, 'figure_facets',
formats=['pdf', 'png'], dpi=300)
将 seaborn 与 matplotlib 子图结合:
# 创建自定义多面板布局
fig, axes = plt.subplots(2, 2, figsize=(7, 6))
# 面板 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')
# 面板 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')
# 面板 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')
# 面板 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()
发表用配色方案
Seaborn 包含多个色盲安全调色板:
# 使用内置色盲调色板(推荐)
sns.set_palette('colorblind')
# 或指定自定义色盲安全颜色(Okabe-Ito)
okabe_ito = ['#E69F00', '#56B4E9', '#009E73', '#F0E442',
'#0072B2', '#D55E00', '#CC79A7', '#000000']
sns.set_palette(okabe_ito)
# 用于热力图和连续数据
sns.heatmap(data, cmap='viridis') # 感知均匀
sns.heatmap(corr, cmap='RdBu_r', center=0) # 发散型,居中
在轴级与图级函数之间选择
轴级函数(如 scatterplot、boxplot、heatmap):
- 在构建自定义多面板布局时使用
- 接受
ax=参数进行精确定位 - 与 matplotlib 子图集成更好
- 对图形组成有更多控制
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控制尺寸
g = sns.relplot(data=df, x='x', y='y', col='category', kind='scatter')
使用 Seaborn 实现统计严谨性
Seaborn 自动计算并显示不确定性:
# 线图:默认显示均值 ± 95% CI
sns.lineplot(data=df, x='time', y='value', hue='treatment',
errorbar=('ci', 95)) # 可改为 'sd'、'se' 等
# 条形图:显示均值及自助法 CI
sns.barplot(data=df, x='treatment', y='response',
errorbar=('ci', 95), capsize=0.1)
# 始终在图注中注明误差类型:
# "误差线表示 95% 置信区间"
发表级 Seaborn 图形的最佳实践
-
始终先设置发表主题:
sns.set_theme(style='ticks', context='paper', font_scale=1.1) -
使用色盲安全调色板:
sns.set_palette('colorblind') -
移除不必要的元素:
sns.despine() # 移除顶部和右侧边框 -
适当控制图形尺寸:
# 轴级:使用 matplotlib figsize fig, ax = plt.subplots(figsize=(3.5, 2.5)) # 图级:使用 height 和 aspect g = sns.relplot(..., height=3, aspect=1.2) -
尽可能显示个体数据点:
sns.boxplot(...) # 汇总统计 sns.stripplot(..., alpha=0.3) # 个体数据点 -
包含带单位的正确标签:
ax.set_xlabel('Time (hours)') ax.set_ylabel('Expression (AU)') -
以正确分辨率导出:
from figure_export import save_publication_figure save_publication_figure(fig, 'figure_name', formats=['pdf', 'png'], dpi=300)
高级 Seaborn 技巧
探索性分析的成对关系图:
# 快速查看所有关系
g = sns.pairplot(data=df, hue='condition',
vars=['gene1', 'gene2', 'gene3'],
corner=True, diag_kind='kde', height=2)
层次聚类热力图:
# 对样本和特征进行聚类
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'})
带边缘分布的联合图:
# 双变量分布及上下文
g = sns.jointplot(data=df, x='gene1', y='gene2',
hue='treatment', kind='scatter',
height=6, ratio=4, marginal_kws={'kde': True})
常见 Seaborn 问题及解决方案
问题:图例超出绘图区域
g = sns.relplot(...)
g._legend.set_bbox_to_anchor((0.9, 0.5))
问题:标签重叠
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
问题:最终尺寸下文字过小
sns.set_context('paper', font_scale=1.2) # 根据需要增大
其他资源
更多 seaborn 详细信息,请参见:
skills/seaborn/SKILL.md—— 全面的 seaborn 文档skills/seaborn/references/examples.md—— 实际用例skills/seaborn/references/function_reference.md—— 完整 API 参考skills/seaborn/references/objects_interface.md—— 现代声明式 API
Plotly
- 交互式图形用于探索
- 导出静态图像用于发表
- 配置为发表质量:
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
资源
参考文档目录
根据需要加载以下文件获取详细信息:
-
publication_guidelines.md:综合最佳实践- 分辨率和文件格式要求
- 排版指南
- 布局与构图规则
- 统计严谨性要求
- 完整发表检查清单
-
color_palettes.md:颜色使用指南- 色盲友好调色板规格及 RGB 值
- 顺序型和发散型颜色映射推荐
- 无障碍测试流程
- 领域特定调色板(基因组学、显微镜)
-
journal_requirements.md:期刊特定规格- 各出版社的技术要求
- 文件格式和 DPI 规格
- 图形尺寸要求
- 快速参考表
-
matplotlib_examples.md:实用代码示例- 10 个完整的工作示例
- 线图、条形图、热力图、多面板图形
- 期刊特定图形示例
- 各库(matplotlib、seaborn、plotly)的使用技巧
脚本目录
使用以下辅助脚本实现自动化:
-
figure_export.py:导出工具save_publication_figure():以多种格式保存,DPI 正确save_for_journal():自动应用期刊特定要求check_figure_size():验证尺寸是否符合期刊规格- 直接运行:
python scripts/figure_export.py查看示例
-
style_presets.py:预配置样式apply_publication_style():应用预设样式(default、nature、science、cell)set_color_palette():快速切换调色板configure_for_journal():一键期刊配置- 直接运行:
python scripts/style_presets.py查看示例
资源文件目录
在图形中使用以下文件:
-
color_palettes.py:可导入的颜色定义- 所有推荐调色板作为 Python 常量
apply_palette()辅助函数- 可直接导入到笔记本/脚本中
-
Matplotlib 样式文件:使用
plt.style.use()加载publication.mplstyle:通用发表质量nature.mplstyle:Nature 期刊规格presentation.mplstyle:海报/幻灯片用大字体
工作流程总结
创建发表级图形的推荐工作流程:
- 规划:确定目标期刊、图形类型和内容
- 配置:为期刊应用合适的样式
from style_presets import configure_for_journal configure_for_journal('nature', 'single') - 创建:使用正确的标签、颜色和统计信息构建图形
- 验证:检查尺寸、字体、颜色和无障碍性
from figure_export import check_figure_size check_figure_size(fig, journal='nature') - 导出:以所需格式保存
from figure_export import save_for_journal save_for_journal(fig, 'figure1', 'nature', 'combination') - 审阅:在手稿上下文中以最终尺寸查看
应避免的常见陷阱
- 字体过小:以最终尺寸打印时文字不可读
- JPEG 格式:切勿在图表中使用 JPEG(会产生伪影)
- 红-绿配色:约 8% 的男性无法区分
- 低分辨率:发表时出现像素化图形
- 缺少单位:始终为轴标注单位
- 3D 效果:扭曲感知,应完全避免
- 图表垃圾:移除不必要的网格线和装饰
- 截断坐标轴:条形图从零开始,除非有科学依据
- 风格不一致:同一手稿中不同图形使用不同字体/颜色
- 没有误差线:始终显示不确定性
最终检查清单
在提交图形之前,请确认:
- 分辨率符合期刊要求(300+ DPI)
- 文件格式正确(图形用矢量,图像用 TIFF)
- 图形尺寸符合期刊规格
- 所有文字在最终尺寸下可读(≥6 pt)
- 颜色色盲友好
- 图形在灰度下可用
- 所有轴已标注单位
- 误差线已标注且说明中已定义
- 面板标签存在且一致
- 无图表垃圾或 3D 效果
- 所有图形字体一致
- 统计显著性已清晰标记
- 图例清晰完整
使用本技能,确保科学图形达到最高发表标准,同时对所有读者保持无障碍可读。