[ SKILL_DOCUMENTATION ]
# Seaborn 常见用例与示例
本文档提供了使用 Seaborn 进行常见数据可视化场景的实用示例。
## 探索性数据分析
### 快速数据集概览
python
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# 加载数据
df = pd.read_csv('data.csv')
# 所有数值变量的成对关系
sns.pairplot(df, hue='target_variable', corner=True, diag_kind='kde')
plt.suptitle('数据集概览', y=1.01)
plt.savefig('overview.png', dpi=300, bbox_inches='tight')
### 分布探索
python
# 跨类别的多重分布
g = sns.displot(
data=df,
x='measurement',
hue='condition',
col='timepoint',
kind='kde',
fill=True,
height=3,
aspect=1.5,
col_wrap=3,
common_norm=False
)
g.set_axis_labels('测量值', '密度')
g.set_titles('{col_name}')
### 相关性分析
python
# 计算相关矩阵
corr = df.select_dtypes(include='number').corr()
# 为上三角创建掩码
mask = np.triu(np.ones_like(corr, dtype=bool))
# 绘制热力图
fig, ax = plt.subplots(figsize=(10, 8))
sns.heatmap(
corr,
mask=mask,
annot=True,
fmt='.2f',
cmap='coolwarm',
center=0,
square=True,
linewidths=1,
cbar_kws={'shrink': 0.8}
)
plt.title('相关矩阵')
plt.tight_layout()
## 科学出版
### 包含不同图表类型的多面板图
python
# 设置出版风格
sns.set_theme(style='ticks', context='paper', font_scale=1.1)
sns.set_palette('colorblind')
# 创建自定义布局的图表
fig = plt.figure(figsize=(12, 8))
gs = fig.add_gridspec(2, 3, hspace=0.3, wspace=0.3)
# 面板 A: 时间序列
ax1 = fig.add_subplot(gs[0, :2])
sns.lineplot(
data=timeseries_df,
x='time',
y='expression',
hue='gene',
style='treatment',
markers=True,
dashes=False,
ax=ax1
)
ax1.set_title('A. 基因表达随时间的变化', loc='left', fontweight='bold')
ax1.set_xlabel('时间 (小时)')
ax1.set_ylabel('表达水平 (AU)')
# 面板 B: 分布比较
ax2 = fig.add_subplot(gs[0, 2])
sns.violinplot(
data=expression_df,
x='treatment',
y='expression',
inner='box',
ax=ax2
)
ax2.set_title('B. 表达分布', loc='left', fontweight='bold')
ax2.set_xlabel('处理')
ax2.set_ylabel('')
# 面板 C: 相关性
ax3 = fig.add_subplot(gs[1, 0])
sns.scatterplot(
data=correlation_df,
x='gene1',
y='gene2