scientific-visualization by davila7/claude-code-templates
npx skills add https://github.com/davila7/claude-code-templates --skill scientific-visualization科学可视化将数据转化为清晰、准确的图表以供发表。使用 matplotlib、seaborn 和 plotly 创建符合期刊要求的图表,包含多面板布局、误差条、显著性标记和色盲安全调色板。为稿件导出 PDF/EPS/TIFF 格式。
此技能应在以下情况使用:
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)
# 以出版格式保存(来自 scripts/figure_export.py)
from figure_export import save_publication_figure
save_publication_figure(fig, 'figure1', formats=['pdf', 'png'], dpi=300)
使用 中的 matplotlib 样式文件应用期刊特定样式:
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
assets/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:
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)
关键要求(详见 references/publication_guidelines.md):
实现方法:
# 使用 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')
始终使用色盲友好调色板(详见 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、cividisPuOr、RdBu、BrBG)jet 或 rainbow 配色方案始终在灰度模式下测试图表以确保可解释性。
字体指南(详见 references/publication_guidelines.md):
实现方法:
# 全局设置字体
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
期刊特定宽度(详见 references/journal_requirements.md):
检查图表尺寸合规性:
from figure_export import check_figure_size
fig = plt.figure(figsize=(3.5, 3)) # Nature 89 mm
check_figure_size(fig, journal='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')
完整代码见 references/matplotlib_examples.md 示例 1。
关键步骤:
使用 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()
完整代码见 references/matplotlib_examples.md 示例 2。
关键步骤:
GridSpec 实现灵活布局完整代码见 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)
工作流程:
检查期刊要求: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')
清单方法(完整清单见 references/publication_guidelines.md):
策略:
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)
始终包含:
带统计的示例:
# 显示个体点与汇总统计
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)
references/matplotlib_examples.mdSeaborn 为统计图形提供了一个基于 matplotlib 构建的高级、面向数据集的接口。它擅长用最少的代码创建出版质量的统计可视化,同时保持与 matplotlib 自定义的完全兼容性。
科学可视化的关键优势:
始终先应用 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()
带置信带的时间序列:
# 带自动 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('Time (hours)')
ax.set_ylabel('Measurement (AU)')
sns.despine()
使用 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 自动计算并显示不确定性:
# 折线图:默认显示均值 ± 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% 置信区间"
始终先设置出版主题:
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)
探索性分析的成对关系:
# 所有关系的快速概览
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})
问题:图例超出绘图区域
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用于探索的交互式图表
导出静态图像用于出版
配置为出版质量:
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:颜色使用指南
journal_requirements.md:期刊特定规范
matplotlib_examples.md:实用代码示例
使用这些辅助脚本进行自动化:
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:可导入的颜色定义
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')
审查:在稿件上下文中以最终尺寸查看
提交图表前,验证:
使用此技能确保科学图表符合最高出版标准,同时对所有读者保持可访问性。
每周安装
449
仓库
GitHub 星标
22.6K
首次出现
Jan 21, 2026
安全审计
安装于
opencode374
claude-code319
gemini-cli314
codex299
cursor277
github-copilot268
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.
This skill should be used when:
import matplotlib.pyplot as plt
import numpy as np
# Apply publication style (from scripts/style_presets.py)
from style_presets import apply_publication_style
apply_publication_style('default')
# Create figure with appropriate size (single column = 3.5 inches)
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)')
# Proper labeling with units
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)
# Save in publication formats (from scripts/figure_export.py)
from figure_export import save_publication_figure
save_publication_figure(fig, 'figure1', formats=['pdf', 'png'], dpi=300)
Apply journal-specific styles using the matplotlib style files in assets/:
import matplotlib.pyplot as plt
# Option 1: Use style file directly
plt.style.use('assets/nature.mplstyle')
# Option 2: Use style_presets.py helper
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()
# ... your plotting code ...
For statistical plots, use seaborn with publication styling:
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')
# 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()
# Save figure
from figure_export import save_publication_figure
save_publication_figure(fig, 'treatment_comparison', formats=['pdf', 'png'], dpi=300)
Critical requirements (detailed in references/publication_guidelines.md):
Implementation:
# Use the figure_export.py script for correct settings
from figure_export import save_publication_figure
# Saves in multiple formats with proper DPI
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')
Always use colorblind-friendly palettes (detailed in references/color_palettes.md):
Recommended: Okabe-Ito palette (distinguishable by all types of color blindness):
# Option 1: Use assets/color_palettes.py
from color_palettes import OKABE_ITO_LIST, apply_palette
apply_palette('okabe_ito')
# Option 2: Manual specification
okabe_ito = ['#E69F00', '#56B4E9', '#009E73', '#F0E442',
'#0072B2', '#D55E00', '#CC79A7', '#000000']
plt.rcParams['axes.prop_cycle'] = plt.cycler(color=okabe_ito)
For heatmaps/continuous data:
viridis, plasma, cividisPuOr, RdBu, BrBG instead)jet or rainbow colormapsAlways test figures in grayscale to ensure interpretability.
Font guidelines (detailed in references/publication_guidelines.md):
Implementation:
# 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
Journal-specific widths (detailed in references/journal_requirements.md):
Check figure size compliance:
from figure_export import check_figure_size
fig = plt.figure(figsize=(3.5, 3)) # 89 mm for Nature
check_figure_size(fig, journal='nature')
Best practices:
Example implementation (see references/matplotlib_examples.md for complete code):
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')
See references/matplotlib_examples.md Example 1 for complete code.
Key steps:
Using seaborn for automatic confidence intervals:
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()
See references/matplotlib_examples.md Example 2 for complete code.
Key steps:
GridSpec for flexible layoutSee references/matplotlib_examples.md Example 4 for complete code.
Key steps:
viridis, plasma, cividis)RdBu_r, PuOr)Using seaborn for correlation matrices:
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)
Workflow:
Check journal requirements: references/journal_requirements.md
Configure matplotlib for journal:
from style_presets import configure_for_journal
configure_for_journal('nature', figure_width='single')
Create figure (will auto-size correctly)
Export with journal specifications:
from figure_export import save_for_journal
save_for_journal(fig, 'figure1', journal='nature', figure_type='line_art')
Checklist approach (full checklist in references/publication_guidelines.md):
Strategy:
assets/color_palettes.pyExample:
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)
Always include:
Example with statistics:
# 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)
# Mark significance
ax.text(1.5, max_y * 1.1, '***', ha='center', fontsize=8)
references/matplotlib_examples.md for extensive examplesSeaborn 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:
Always apply matplotlib publication styles first, then configure seaborn:
import seaborn as sns
import matplotlib.pyplot as plt
from style_presets import apply_publication_style
# Apply publication style
apply_publication_style('default')
# Configure seaborn for publication
sns.set_theme(style='ticks', context='paper', font_scale=1.1)
sns.set_palette('colorblind') # Use colorblind-safe palette
# 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
Statistical comparisons:
# 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:
# 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:
# 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:
# 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()
Using FacetGrid for automatic faceting:
# 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()
# Save with correct 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:
# Create custom multi-panel layout
fig, axes = plt.subplots(2, 2, figsize=(7, 6))
# Panel A: Scatter with regression
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
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
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
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 includes several colorblind-safe palettes:
# Use built-in colorblind palette (recommended)
sns.set_palette('colorblind')
# Or specify custom colorblind-safe colors (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
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
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
g = sns.relplot(data=df, x='x', y='y', col='category', kind='scatter')
Seaborn automatically computes and displays uncertainty:
# Line plot: shows mean ± 95% CI by default
sns.lineplot(data=df, x='time', y='value', hue='treatment',
errorbar=('ci', 95)) # Can change to 'sd', 'se', etc.
# Bar plot: shows mean with bootstrapped CI
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"
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() # Remove top and right spines
Control figure size appropriately:
# 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:
sns.boxplot(...) # Summary statistics
sns.stripplot(..., alpha=0.3) # Individual points
Include proper labels with units:
Pairwise relationships for exploratory analysis:
# 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:
# 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:
# 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})
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) # Increase if needed
For more detailed seaborn information, see:
scientific-packages/seaborn/SKILL.md - Comprehensive seaborn documentationscientific-packages/seaborn/references/examples.md - Practical use casesscientific-packages/seaborn/references/function_reference.md - Complete API referencescientific-packages/seaborn/references/objects_interface.md - Modern declarative APIInteractive 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', # ... see matplotlib_examples.md Example 8 ) fig.write_image('figure.png', scale=3) # scale=3 gives ~300 DPI
Load these as needed for detailed information:
publication_guidelines.md : Comprehensive best practices
color_palettes.md : Color usage guide
journal_requirements.md : Journal-specific specifications
matplotlib_examples.md : Practical code examples
Use these helper scripts for automation:
figure_export.py : Export utilities
save_publication_figure(): Save in multiple formats with correct DPIsave_for_journal(): Use journal-specific requirements automaticallycheck_figure_size(): Verify dimensions meet journal specspython scripts/figure_export.py for examplesstyle_presets.py : Pre-configured styles
apply_publication_style(): Apply preset styles (default, nature, science, cell)set_color_palette(): Quick palette switchingUse these files in figures:
color_palettes.py : Importable color definitions
apply_palette() helper functionMatplotlib style files : Use with plt.style.use()
publication.mplstyle: General publication qualitynature.mplstyle: Nature journal specificationspresentation.mplstyle: Larger fonts for posters/slidesRecommended workflow for creating publication figures:
Plan : Determine target journal, figure type, and content
Configure : Apply appropriate style for journal
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
from figure_export import check_figure_size
check_figure_size(fig, journal='nature')
Export : Save in required formats
from figure_export import save_for_journal
save_for_journal(fig, 'figure1', 'nature', 'combination')
Review : View at final size in manuscript context
Before submitting figures, verify:
Use this skill to ensure scientific figures meet the highest publication standards while remaining accessible to all readers.
Weekly Installs
449
Repository
GitHub Stars
22.6K
First Seen
Jan 21, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode374
claude-code319
gemini-cli314
codex299
cursor277
github-copilot268
DOCX文件创建、编辑与分析完整指南 - 使用docx-js、Pandoc和Python脚本
41,800 周安装
OpenAPI 转 TypeScript 工具 - 自动生成 API 接口与类型守卫
563 周安装
数据库模式设计器 - 内置最佳实践,自动生成生产级SQL/NoSQL数据库架构
564 周安装
Rust Unsafe代码检查器 - 安全使用Unsafe Rust的完整指南与最佳实践
564 周安装
.NET并发编程模式指南:async/await、Channels、Akka.NET选择决策树
565 周安装
韩语语法检查器 - 基于国立国语院标准的拼写、空格、语法、标点错误检测与纠正
565 周安装
技能安全扫描器 - 检测Claude技能安全漏洞,防范提示注入与恶意代码
565 周安装
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)
configure_for_journal(): One-command journal configurationpython scripts/style_presets.py to see examples