| name | scientific-visualization |
| description | 面向发表级图表的元技能。适用于需要多面板布局、显著性标注、误差线、色盲安全配色和特定期刊格式要求的投稿图表。协调 matplotlib、seaborn、plotly 及其发表风格;若只是快速探索,直接使用 seaborn 或 plotly 即可。 |
| license | MIT license |
| metadata | {"skill-author":"K-Dense Inc.","acadclaw":{"profiles":["coder"],"produces":["plots"],"consumes":["experiment_results"]}} |
科学可视化
概述
科学可视化的目标,是把数据转成适合发表的清晰、准确图表。它强调多面板布局、误差线、显著性标记与色盲安全配色,并支持使用 matplotlib、seaborn、plotly 导出 PDF、EPS、TIFF 等投稿格式。
何时使用这个技能
当你遇到以下场景时,应优先使用这个技能:
- 为科研论文创建图表或可视化内容
- 为期刊投稿准备图形(Nature、Science、Cell、PLOS 等)
- 确保图表对色盲用户友好并满足可访问性要求
- 制作风格统一的多面板图
- 以正确分辨率和格式导出图表
- 遵循特定期刊的投稿规范
- 改进已有图表以满足发表标准
- 制作在彩色和灰度打印下都可辨识的图表
快速开始
基础发表级图表示例
import matplotlib.pyplot as plt
import numpy as np
from style_presets import apply_publication_style
apply_publication_style('default')
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)
from figure_export import save_publication_figure
save_publication_figure(fig, 'figure1', formats=['pdf', 'png'], dpi=300)
使用预设风格
可通过 assets/ 中的 matplotlib 样式文件套用特定期刊风格:
import matplotlib.pyplot as plt
plt.style.use('assets/nature.mplstyle')
from style_presets import configure_for_journal
configure_for_journal('nature', figure_width='single')
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
- 线稿图(graphs、plots):600-1200 DPI,或直接使用矢量格式
- 矢量格式(优先):PDF、EPS、SVG
- 位图格式:TIFF、PNG(科研数据图不要使用 JPEG)
实现方式:
from figure_export import save_publication_figure
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 配色(对常见色觉缺陷都较易区分):
from color_palettes import OKABE_ITO_LIST, apply_palette
apply_palette('okabe_ito')
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(通常加粗)
- 标签建议使用 sentence case,如
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: Single 89 mm, Double 183 mm
- Science: Single 55 mm, Double 175 mm
- Cell: Single 85 mm, Double 178 mm
检查图尺寸是否合规:
from figure_export import check_figure_size
fig = plt.figure(figsize=(3.5, 3))
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 的 Example 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 的 Example 2。
关键步骤:
- 使用
GridSpec 构造灵活布局
- 保证各面板风格一致
- 添加加粗面板标签(A、B、C 等)
- 对齐相关面板
- 确保最终尺寸下所有文字都可读
任务 3:创建使用正确色图的热图
完整代码见 references/matplotlib_examples.md 的 Example 4。
关键步骤:
- 使用感知均匀色图(
viridis、plasma、cividis)
- 添加带标签的 colorbar
- 对发散型数据,使用色盲友好的发散色图(
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 中已验证的配色
- 增加冗余编码,如线型、marker、纹理
- 使用色盲模拟器进行测试
- 确保灰度下也可读
示例:
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
- 对投稿细节的控制力最强
- 最适合复杂多面板图
- 可结合提供的 style 文件保持格式一致
- 更完整的示例见
references/matplotlib_examples.md
Seaborn
Seaborn 是建立在 matplotlib 之上的高层统计绘图库,偏向数据集导向接口。它非常适合用较少代码快速生成投稿质量的统计图,同时保留与 matplotlib 定制能力的兼容性。
在科学可视化中的主要优势:
- 可自动进行统计估计和置信区间绘制
- 内建多面板分面支持(faceting)
- 默认就有较好的色盲友好配色支持
- 基于 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')
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()
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))
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.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.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.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 = ['#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)
何时使用 Axes-Level 与 Figure-Level 接口
Axes-level functions(如 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)
Figure-level functions(如 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
g = sns.relplot(data=df, x='x', y='y', col='category', kind='scatter')
Statistical Rigor with Seaborn
Seaborn automatically computes and displays uncertainty:
sns.lineplot(data=df, x='time', y='value', hue='treatment',
errorbar=('ci', 95))
sns.barplot(data=df, x='treatment', y='response',
errorbar=('ci', 95), capsize=0.1)
Best Practices for Publication-Ready Seaborn Figures
-
Always set publication theme first:
sns.set_theme(style='ticks', context='paper', font_scale=1.1)
-
Use colorblind-safe palettes:
sns.set_palette('colorblind')
-
Remove unnecessary elements:
sns.despine()
-
Control figure size appropriately:
fig, ax = plt.subplots(figsize=(3.5, 2.5))
g = sns.relplot(..., height=3, aspect=1.2)
-
Show individual data points when possible:
sns.boxplot(...)
sns.stripplot(..., alpha=0.3)
-
Include proper labels with units:
ax.set_xlabel('Time (hours)')
ax.set_ylabel('Expression (AU)')
-
Export at correct resolution:
from figure_export import save_publication_figure
save_publication_figure(fig, 'figure_name',
formats=['pdf', 'png'], dpi=300)
Advanced Seaborn Techniques
Pairwise relationships for exploratory analysis:
g = sns.pairplot(data=df, hue='condition',
vars=['gene1', 'gene2', 'gene3'],
corner=True, diag_kind='kde', height=2)
Hierarchical clustering heatmap:
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:
g = sns.jointplot(data=df, x='gene1', y='gene2',
hue='treatment', kind='scatter',
height=6, ratio=4, marginal_kws={'kde': True})
Common Seaborn Issues and Solutions
Issue: Legend outside plot area
g = sns.relplot(...)
g._legend.set_bbox_to_anchor((0.9, 0.5))
Issue: Overlapping labels
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
Issue: Text too small at final size
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
Plotly
- Interactive figures for exploration
- Export static images for publication
- Configure for publication quality:
fig.update_layout(
font=dict(family='Arial, sans-serif', size=10),
plot_bgcolor='white',
)
fig.write_image('figure.png', scale=3)
Resources
References Directory
按需加载以下文档以获取详细信息:
-
publication_guidelines.md: 综合最佳实践
- 分辨率与文件格式要求
- 字体排版规范
- 布局与构图规则
- 统计严谨性要求
- 完整投稿检查清单
-
color_palettes.md: 配色使用指南
- 带 RGB 数值的色盲友好配色规范
- 顺序色图和发散色图建议
- 可访问性测试流程
- 领域专用配色(如基因组学、显微成像)
-
journal_requirements.md: 期刊专属技术规范
- 不同出版社的技术要求
- 文件格式与 DPI 规范
- 图件尺寸要求
- 快速参考表
-
matplotlib_examples.md: 实用代码示例
- 10 个完整可运行示例
- 折线图、柱状图、热图、多面板图
- 期刊定制图表示例
- 各绘图库使用提示(matplotlib、seaborn、plotly)
Scripts Directory
使用这些辅助脚本完成自动化处理:
-
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 查看示例
Assets Directory
在图件中使用以下资源文件:
工作流概览
推荐的投稿图件工作流:
- 规划:确定目标期刊、图件类型和内容
- 配置:为目标期刊应用合适样式
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 效果:会扭曲感知,应完全避免
- 图表杂讯:删除不必要的网格线和装饰元素
- 截断坐标轴:柱状图应从零开始,除非有充分科学理由
- 风格不一致:同一篇稿件中的图件不应使用不同字体或配色体系
- 没有误差条:必须展示不确定性
最终检查清单
投稿前请确认:
Use this skill to ensure scientific figures meet the highest publication standards while remaining accessible to all readers.