mcpField
S
seaborn

seaborn

github.com/tondevrel数据与数据库25165 次安装39 周前更新
代码仓库

关于 seaborn

seaborn 是用于数据探索和统计绘图的 Python 可视化库。它面向使用 Pandas DataFrame 的分析场景,提供高层绘图、分面布局,并可结合 Matplotlib 调整图表。

主要功能

  1. 01统计关系图与分布图
  2. 02分类数据对比图
  3. 03带不确定性的回归图
  4. 04热图与聚类矩阵
  5. 05分面多图布局
  6. 06主题与调色板

适用场景

  1. 01探索数据集变量间关系
  2. 02比较不同类别的分布
  3. 03展示带置信区间的趋势
  4. 04用热图概览矩阵数据

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/tondevrel/scientific-agent-skills --skill seaborn

安装后在 Claude Code 中输入/seaborn确认已加载。

详细介绍

Seaborn - 统计数据可视化

Seaborn 通过精美且信息丰富的统计图,帮助你探索和理解数据。它可以自动完成计算置信区间、汇总数据和创建分面网格等复杂任务。

适用场景

  • 可视化多个变量之间的复杂关系(relplot)
  • 检查单变量和双变量分布(displot、kdeplot)
  • 使用统计汇总值比较类别(catplot、boxplot、violinplot)
  • 可视化线性回归模型及其不确定性(regplot、lmplot)
  • 为大型矩阵创建热力图和聚类图
  • 根据数据子集构建多图网格(FacetGrid)
  • 为 Matplotlib 图形设置高级美学主题

参考文档

官方文档:https://seaborn.pydata.org/
示例集:https://seaborn.pydata.org/examples/index.html
搜索模式:sns.load_dataset、sns.relplot、sns.catplot、sns.set_theme、sns.heatmap

核心原则

Figure 级函数与 Axes 级函数
函数类型示例主要特点
Figure 级relplot、displot、catplot创建自己的图形(FacetGrid)。适合子图(col、row)。
Axes 级scatterplot、histplot、boxplot绘制到特定的 ax 上。适合与 Matplotlib 布局集成。
适合使用 Seaborn 的场景
  • 统计分析和探索性数据研究(EDA)。
  • 直接使用“整洁”(长格式)的 Pandas DataFrame。
  • 自动计算 95% 置信区间(误差线)。
  • 快速更换视觉主题和调色板。
不适合使用 Seaborn 的场景
  • 非常底层的自定义图形(使用 Matplotlib)。
  • 交互式 Web 可视化(使用 Plotly)。
  • 3D 绘图(使用 Matplotlib mplot3d 或 PyVista)。
  • 网络图(使用 NetworkX 和 Matplotlib)。

快速参考

安装
pip install seaborn
标准导入
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# Apply the default theme
sns.set_theme()
基本模式 - 整洁数据映射
import seaborn as sns

# Load an example dataset
tips = sns.load_dataset("tips")

# Create a scatter plot with semantic mapping
sns.relplot(
    data=tips,
    x="total_bill", y="tip", 
    hue="smoker", style="time", size="size",
)
plt.show()

关键规则

✅ 应该做
  • 使用整洁数据 - 确保 DataFrame 采用“长格式”(每条观测占一行)。
  • 优先使用 Figure 级函数 - 使用 relplot/displot/catplot,以获得更好的默认布局和分面效果。
  • 使用 data= 参数 - 始终传入 DataFrame,让代码保持简洁。
  • 设置主题 - 在脚本开头使用 sns.set_theme(style="whitegrid", palette="muted")。
  • 利用 hue - 使用语义颜色映射,为 2D 图添加额外维度。
  • 注意使用场景 - 发布时使用 sns.set_context("paper"),演示时使用 "talk"。
❌ 不应该做
  • 手动传入一维数组 - 避免使用 sns.plot(x_array, y_array);这样会忽略 Pandas 集成的优势。
  • 忽略索引 - 与 Matplotlib 不同,Seaborn 基本会忽略 DataFrame 索引(请改用列)。
  • 让图表过于拥挤 - 过多的语义映射(hue、size、style)会使图表难以辨读。
  • 忘记 Matplotlib - 请记住,Seaborn 函数会返回 Matplotlib 对象;使用 ax.set_title() 进行调整。

反模式(绝对不要)

import seaborn as sns
import matplotlib.pyplot as plt

# ❌ BAD: Iterating through groups to plot manually
for s in df['species'].unique():
    subset = df[df['species'] == s]
    plt.scatter(subset['x'], subset['y'], label=s)

# ✅ GOOD: Let Seaborn handle grouping and legend
sns.scatterplot(data=df, x='x', y='y', hue='species')

# ❌ BAD: Mixing Seaborn and Matplotlib titles incorrectly
sns.displot(data=df, x='val')
plt.title("My Title") # ⚠️ Might apply to the wrong axis in a FacetGrid!

# ✅ GOOD: Use the returned object
g = sns.displot(data=df, x='val')
g.set_axis_labels("Value", "Count")
g.figure.suptitle("Correct Global Title", y=1.05)

关系图(relplot)

散点图和折线图
# Multi-faceted scatter plot
sns.relplot(
    data=tips, x="total_bill", y="tip",
    col="time", hue="day", style="sex",
    kind="scatter"
)

# Line plot with automatic aggregation (mean + 95% CI)
fmri = sns.load_dataset("fmri")
sns.relplot(
    data=fmri, x="timepoint", y="signal",
    hue="event", style="region",
    kind="line", errorbar="sd" # "sd" for standard deviation instead of CI
)

分布图(displot)

直方图和 KDE
penguins = sns.load_dataset("penguins")

# Histogram with Kernel Density Estimate
sns.displot(data=penguins, x="flipper_length_mm", hue="species", kde=True)

# Bivariate distribution (Heatmap style)
sns.displot(data=penguins, x="bill_length_mm", y="bill_depth_mm", hue="species", kind="kde")

# Empirical Cumulative Distribution (ECDF)
sns.displot(data=penguins, x="flipper_length_mm", hue="species", kind="ecdf")

分类图(catplot)

类别内的比较和分布
# Boxplot (Show quartiles and outliers)
sns.catplot(data=tips, x="day", y="total_bill", kind="box")

# Violin plot (Show density and quartiles)
sns.catplot(data=tips, x="day", y="total_bill", hue="sex", kind="violin", split=True)

# Swarm plot (Show every point without overlap)
sns.catplot(data=tips, x="day", y="total_bill", kind="swarm")

# Bar plot (Show mean and error bars)
sns.catplot(data=tips, x="day", y="total_bill", kind="bar", errorbar=("pi", 95))

回归图

可视化线性趋势
# Simple regression with scatter
sns.regplot(data=tips, x="total_bill", y="tip")

# Faceted regression
sns.lmplot(data=tips, x="total_bill", y="tip", col="smoker", hue="time")

# Logistic regression (for binary data)
sns.lmplot(data=df, x="variable", y="binary_outcome", logistic=True)

矩阵图

热力图和聚类
flights = sns.load_dataset("flights").pivot(index="month", columns="year", values="passengers")

# Heatmap
plt.figure(figsize=(10, 8))
sns.heatmap(flights, annot=True, fmt="d", cmap="YlGnBu")

# Cluster map (Hierarchical clustering)
sns.clustermap(flights, standard_scale=1, cmap="mako")

网格对象(高级)

自定义多图布局
# JointPlot (Scatter + Marginals)
sns.jointplot(data=penguins, x="bill_length_mm", y="bill_depth_mm", hue="species", kind="kde")

# PairPlot (All-against-all relations)
sns.pairplot(data=penguins, hue="species", corner=True)

# Custom FacetGrid
g = sns.FacetGrid(tips, col="time",  row="sex")
g.map(sns.scatterplot, "total_bill", "tip")

样式和美学

主题和调色板
# Set overall look
sns.set_style("darkgrid") # white, dark, whitegrid, ticks
sns.set_context("talk")   # paper, notebook, talk, poster

# Custom palettes
sns.set_palette("husl") # Set global palette
my_pal = sns.color_palette("rocket", as_cmap=True) # Get palette as object

# Viewing a palette
sns.palplot(sns.color_palette("Set2"))

实用工作流

1. 探索性数据分析(EDA)流程
def initial_eda(df, target_col):
    """Generate basic visual summary of a dataset."""
    # 1. Distribution of target
    sns.displot(data=df, x=target_col, kde=True)
    
    # 2. Pairwise relations of numeric features
    sns.pairplot(data=df, hue=target_col if df[target_col].nunique() < 10 else None)
    
    # 3. Correlation heatmap
    plt.figure(figsize=(12, 10))
    sns.heatmap(df.corr(numeric_only=True), annot=True, cmap='coolwarm', fmt=".2f")

# initial_eda(iris, "species")
2. 科学结果比较
def plot_experiment_results(df):
    """Plot results of an experiment with multiple conditions."""
    g = sns.catplot(
        data=df, kind="bar",
        x="condition", y="metric", hue="group",
        palette="viridis", alpha=.6, height=6
    )
    g.despine(left=True)
    g.set_axis_labels("Experimental Condition", "Accuracy (%)")
    g.legend.set_title("User Group")
    return g
3. 按类别查看时间序列趋势
def plot_trends(df, time_col, val_col, cat_col):
    """Visualizes trends over time with confidence intervals."""
    plt.figure(figsize=(12, 6))
    sns.lineplot(
        data=df, x=time_col, y=val_col, hue=cat_col,
        marker="o", err_style="bars"
    )
    plt.xticks(rotation=45)
    plt.tight_layout()

常见问题与解决方案

将图例放在图表外
# ❌ Problem: Legend covers data in narrow plots
# ✅ Solution: Move legend manually using Matplotlib logic
g = sns.scatterplot(data=tips, x="total_bill", y="tip", hue="day")
sns.move_legend(g, "upper left", bbox_to_anchor=(1, 1))
大型数据导致性能缓慢
# ❌ Problem: sns.pairplot(large_df) hangs
# ✅ Solution: Sample data or use simpler plots
sns.pairplot(df.sample(1000), hue='category') 
# OR use hist instead of scatter
sns.jointplot(data=df, x='x', y='y', kind="hist")
标签重叠
# ❌ Problem: Categorical labels on X-axis overlap
# ✅ Solution: Rotate labels using Matplotlib
g = sns.boxplot(data=df, x='very_long_category_name', y='value')
g.set_xticklabels(g.get_xticklabels(), rotation=45, horizontalalignment='right')

最佳实践

  1. 使用整洁的数据格式 - 确保 DataFrame 为长格式(每行对应一个观测值)
  2. 优先使用图形级函数 - 使用 relplot、displot 和 catplot,以获得更好的默认布局和分面效果
  3. 始终使用 data= 参数 - 直接传入 DataFrame,让代码更简洁易读
  4. 尽早设置主题 - 在脚本开头使用 sns.set_theme(),确保样式一致
  5. 善用语义映射 - 使用 hue、size 和 style 为图表添加维度
  6. 选择合适的上下文 - 发表论文时使用 sns.set_context("paper"),演示时使用 "talk"
  7. 记住 Seaborn 返回的是 Matplotlib 对象 - 使用 ax.set_title() 等 Matplotlib 方法进行微调
  8. 避免图表过于拥挤 - 限制语义映射的数量,以保持可读性
  9. 使用图形级函数进行分面 - 它们会自动处理子图布局
  10. 对大型数据集进行采样 - 绘图前使用 df.sample(),以提升处理大型数据时的性能

Seaborn 提供了高级抽象,让统计可视化变得轻松愉悦,只需付出极少努力即可生成精美、达到出版质量的图形。

评论

支持 Markdown