name: 科学可视化 description: “使用matplotlib/seaborn/plotly创建出版物图表。多面板布局、误差棒、显著性标记、色盲安全、导出PDF/EPS/TIFF,用于期刊就绪的科学图表。”
科学可视化
概述
科学可视化将数据转化为清晰、准确的图表以供发表。使用多面板布局、误差棒、显著性标记和色盲安全调色板创建期刊就绪的图表。使用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('时间(秒)')
ax.set_ylabel('振幅(mV)')
ax.legend(frameon=False)
# 移除不必要的边框
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
# 以出版物格式保存(来自scripts/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('响应(μ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)”
- 始终在括号中包含单位
实现:
# 全局设置字体
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('时间(小时)')
ax.set_ylabel('测量值(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 DataFrames的数据集导向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('响应(μ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('基因表达(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()
时间序列带置信带:
# 线图带自动CI计算
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('时间(小时)')
ax.set_ylabel('测量值(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('剂量(μM)', '响应(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('时间(小时)') ax.set_ylabel('表达(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分数'})
带边缘的联合分布:
# 带上下文的二元分布
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信息见:
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
- 探索的交互式图表
- 导出静态图像供出版
- 配置出版物质量:
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():应用预设样式(默认、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效果
- [ ] 所有图表字体一致
- [ ] 统计显著性清晰标记
- [ ] 图例清晰完整
使用此技能确保科学图表满足最高出版标准,同时对所有读者可访问。