mcpField
S
seaborn

seaborn

github.com/jackspace数据与数据库1638 次安装12 周前更新
代码仓库

关于 seaborn

Seaborn 是用于 Python 统计图形的可视化库,面向数据分析和研究工作。它提供面向数据集的绘图接口、统计估算及多面板图表,并可与 Matplotlib 配合定制。

主要功能

  1. 01绘制关系、分布和分类图
  2. 02提供回归图与矩阵图
  3. 03通过语义映射编码颜色和样式
  4. 04自动聚合并估算置信区间
  5. 05使用分面网格构建多面板图
  6. 06支持声明式 Objects 接口

适用场景

  1. 01探索变量之间的关系
  2. 02比较不同类别的数据分布
  3. 03查看数据集的分布形态
  4. 04制作分面统计图表

安装

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

$npx skills add https://github.com/jackspace/claudeskillz --skill seaborn

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

附带文件SKILL.json

详细介绍

Seaborn 统计可视化

概述

Seaborn 是一个 Python 可视化库,用于创建达到出版质量的统计图形。使用此技能可以以最少的代码进行面向数据集的绘图、多变量分析、自动统计估计以及复杂的多面板图形绘制。

设计理念

Seaborn 遵循以下核心原则:

  1. 面向数据集:直接使用 DataFrame 和具名变量,而非抽象坐标
  2. 语义映射:自动将数据值转换为视觉属性(颜色、大小、样式)
  3. 统计感知:内置聚合、误差估计和置信区间
  4. 美学默认值:开箱即用的出版级主题和调色板
  5. Matplotlib 集成:在需要时可与 matplotlib 自定义功能完全兼容

快速开始

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

# Load example dataset
df = sns.load_dataset('tips')

# Create a simple visualization
sns.scatterplot(data=df, x='total_bill', y='tip', hue='day')
plt.show()

核心绘图接口

函数接口(传统)

函数接口提供按可视化类型组织的专用绘图函数。每个类别都有轴级函数(绘制到单个坐标轴)和图形级函数(通过分面管理整个图形)。

使用场景:

  • 快速探索性分析
  • 单一目的的图形绘制
  • 需要特定图形类型时
对象接口(现代)

seaborn.objects 接口提供类似 ggplot2 的声明式、可组合 API。通过链式方法指定数据映射、标记、变换和比例来构建可视化。

使用场景:

  • 复杂的分层可视化
  • 需要对变换进行细粒度控制时
  • 构建自定义图形类型
  • 程序化图形生成
from seaborn import objects as so

# Declarative syntax
(
    so.Plot(data=df, x='total_bill', y='tip')
    .add(so.Dot(), color='day')
    .add(so.Line(), so.PolyFit())
)

按类别划分的绘图函数

关系图(变量之间的关系)

用于: 探索两个或多个变量之间的相互关系

  • scatterplot() - 将单个观测值显示为点
  • lineplot() - 显示趋势和变化(自动聚合并计算 CI)
  • relplot() - 具有自动分面功能的图形级接口

关键参数:

  • x、y - 主要变量
  • hue - 用于附加分类/连续变量的颜色编码
  • size - 点/线大小编码
  • style - 标记/线型样式编码
  • col、row - 分面为多个子图(仅图形级)
# Scatter with multiple semantic mappings
sns.scatterplot(data=df, x='total_bill', y='tip',
                hue='time', size='size', style='sex')

# Line plot with confidence intervals
sns.lineplot(data=timeseries, x='date', y='value', hue='category')

# Faceted relational plot
sns.relplot(data=df, x='total_bill', y='tip',
            col='time', row='sex', hue='smoker', kind='scatter')
分布图(单变量和双变量分布)

用于: 理解数据分布范围、形状和概率密度

  • histplot() - 基于柱状的频率分布,支持灵活的分箱
  • kdeplot() - 使用高斯核的平滑密度估计
  • ecdfplot() - 经验累积分布(无需调整参数)
  • rugplot() - 单个观测值的刻度标记
  • displot() - 单变量和双变量分布的图形级接口
  • jointplot() - 带边际分布的双变量图
  • pairplot() - 数据集中两两关系的矩阵图

关键参数:

  • x、y - 变量(单变量时 y 可选)
  • hue - 按类别分离分布
  • stat - 归一化方式:"count"、"frequency"、"probability"、"density"
  • bins / binwidth - 直方图分箱控制
  • bw_adjust - KDE 带宽乘数(值越大越平滑)
  • fill - 填充曲线下面积
  • multiple - 如何处理 hue:"layer"、"stack"、"dodge"、"fill"
# Histogram with density normalization
sns.histplot(data=df, x='total_bill', hue='time',
             stat='density', multiple='stack')

# Bivariate KDE with contours
sns.kdeplot(data=df, x='total_bill', y='tip',
            fill=True, levels=5, thresh=0.1)

# Joint plot with marginals
sns.jointplot(data=df, x='total_bill', y='tip',
              kind='scatter', hue='time')

# Pairwise relationships
sns.pairplot(data=df, hue='species', corner=True)
分类图(跨类别比较)

用于: 比较离散类别之间的分布或统计量

分类散点图:

  • stripplot() - 带抖动的点,展示所有观测值
  • swarmplot() - 不重叠的点(蜂群算法)

分布比较:

  • boxplot() - 四分位数与离群值
  • violinplot() - KDE + 四分位数信息
  • boxenplot() - 适用于较大数据集的增强箱线图

统计估计:

  • barplot() - 均值/聚合值及置信区间
  • pointplot() - 点估计及连接线
  • countplot() - 每个类别的观测值计数

图形级:

  • catplot() - 分面分类图(设置 kind 参数)

关键参数:

  • x、y - 变量(通常其中一个是分类变量)
  • hue - 额外的分类分组
  • order、hue_order - 控制类别顺序
  • dodge - 将 hue 层级并排分开
  • orient - "v"(垂直)或 "h"(水平)
  • kind - catplot 的绘图类型:"strip"、"swarm"、"box"、"violin"、"bar"、"point"
# Swarm plot showing all points
sns.swarmplot(data=df, x='day', y='total_bill', hue='sex')

# Violin plot with split for comparison
sns.violinplot(data=df, x='day', y='total_bill',
               hue='sex', split=True)

# Bar plot with error bars
sns.barplot(data=df, x='day', y='total_bill',
            hue='sex', estimator='mean', errorbar='ci')

# Faceted categorical plot
sns.catplot(data=df, x='day', y='total_bill',
            col='time', kind='box')
回归图(线性关系)

用于: 可视化线性回归与残差

  • regplot() - 坐标轴级回归图,含散点 + 拟合线
  • lmplot() - 图形级,支持分面
  • residplot() - 用于评估模型拟合的残差图

关键参数:

  • x、y - 要回归的变量
  • order - 多项式回归阶数
  • logistic - 拟合逻辑回归
  • robust - 使用稳健回归(对离群值不那么敏感)
  • ci - 置信区间宽度(默认 95)
  • scatter_kws、line_kws - 自定义散点和线条属性
# Simple linear regression
sns.regplot(data=df, x='total_bill', y='tip')

# Polynomial regression with faceting
sns.lmplot(data=df, x='total_bill', y='tip',
           col='time', order=2, ci=95)

# Check residuals
sns.residplot(data=df, x='total_bill', y='tip')
矩阵图(矩形数据)

用于: 可视化矩阵、相关性和网格结构数据

  • heatmap() - 带注释的颜色编码矩阵
  • clustermap() - 层次聚类热力图

关键参数:

  • data - 二维矩形数据集(DataFrame 或数组)
  • annot - 在单元格中显示数值
  • fmt - 注释的格式字符串(例如 ".2f")
  • cmap - 颜色映射名称
  • center - 颜色映射中心的值(用于发散型颜色映射)
  • vmin、vmax - 颜色刻度范围
  • square - 强制单元格为正方形
  • linewidths - 单元格之间的间隙
# Correlation heatmap
corr = df.corr()
sns.heatmap(corr, annot=True, fmt='.2f',
            cmap='coolwarm', center=0, square=True)

# Clustered heatmap
sns.clustermap(data, cmap='viridis',
               standard_scale=1, figsize=(10, 10))

多图网格

Seaborn 提供网格对象,用于创建复杂的多面板图形:

FacetGrid

基于分类变量创建子图。通过图形级函数(relplot、displot、catplot)调用时最有用,但也可直接用于自定义绘图。

g = sns.FacetGrid(df, col='time', row='sex', hue='smoker')
g.map(sns.scatterplot, 'total_bill', 'tip')
g.add_legend()
PairGrid

展示数据集中所有变量之间的两两关系。

g = sns.PairGrid(df, hue='species')
g.map_upper(sns.scatterplot)
g.map_lower(sns.kdeplot)
g.map_diag(sns.histplot)
g.add_legend()
JointGrid

将双变量图与边缘分布结合起来。

g = sns.JointGrid(data=df, x='total_bill', y='tip')
g.plot_joint(sns.scatterplot)
g.plot_marginals(sns.histplot)

图形级与坐标轴级函数

理解这一区别对于有效使用 seaborn 至关重要:

坐标轴级函数
  • 绘制到单个 matplotlib Axes 对象上
  • 易于集成到复杂的 matplotlib 图形中
  • 接受 ax= 参数以精确放置
  • 返回 Axes 对象
  • 示例:scatterplot、histplot、boxplot、regplot、heatmap

使用场景:

  • 构建自定义多图布局
  • 组合不同的绘图类型
  • 需要 matplotlib 级别的控制
  • 与现有 matplotlib 代码集成
fig, axes = plt.subplots(2, 2, figsize=(10, 10))
sns.scatterplot(data=df, x='x', y='y', ax=axes[0, 0])
sns.histplot(data=df, x='x', ax=axes[0, 1])
sns.boxplot(data=df, x='cat', y='y', ax=axes[1, 0])
sns.kdeplot(data=df, x='x', y='y', ax=axes[1, 1])
图形级函数
  • 管理整个图形,包括所有子图
  • 通过 col 和 row 参数实现内置分面
  • 返回 FacetGrid、JointGrid 或 PairGrid 对象
  • 使用 height 和 aspect 进行尺寸设置(针对每个子图)
  • 无法放置在现有图形中
  • 示例:relplot、displot、catplot、lmplot、jointplot、pairplot

使用场景:

  • 分面可视化(小多图)
  • 快速探索性分析
  • 一致的多面板布局
  • 不需要与其他绘图类型组合
# Automatic faceting
sns.relplot(data=df, x='x', y='y', col='category', row='group',
            hue='type', height=3, aspect=1.2)

数据结构要求

长格式数据(首选)

每个变量是一列,每个观测是一行。这种"整洁"格式提供了最大的灵活性:

# Long-form structure
   subject  condition  measurement
0        1    control         10.5
1        1  treatment         12.3
2        2    control          9.8
3        2  treatment         13.1

优势:

  • 适用于所有 seaborn 函数
  • 易于将变量重新映射到视觉属性
  • 支持任意复杂度
  • 适合 DataFrame 操作
宽格式数据

变量分布在多列中。适用于简单的矩形数据:

# Wide-form structure
   control  treatment
0     10.5       12.3
1      9.8       13.1

使用场景:

  • 简单时间序列
  • 相关性矩阵
  • 热力图
  • 数组数据的快速绘图

将宽格式转换为长格式:

df_long = df.melt(var_name='condition', value_name='measurement')

调色板

Seaborn 为不同数据类型提供了精心设计的调色板:

定性调色板(分类数据)

通过色相变化区分类别:

  • "deep" - 默认,鲜艳的颜色
  • "muted" - 更柔和,饱和度较低
  • "pastel" - 浅色,低饱和度
  • "bright" - 高饱和度
  • "dark" - 深色值
  • "colorblind" - 适合色觉缺陷人群
sns.set_palette("colorblind")
sns.color_palette("Set2")
顺序调色板(有序数据)

展示从低值到高值的渐变:

  • "rocket"、"mako" - 宽亮度范围(适合热力图)
  • "flare"、"crest" - 受限亮度(适合点/线)
  • "viridis"、"magma"、"plasma" - Matplotlib 感知均匀
sns.heatmap(data, cmap='rocket')
sns.kdeplot(data=df, x='x', y='y', cmap='mako', fill=True)
发散调色板(居中数据)

强调与中点的偏差:

  • "vlag" - 蓝色到红色
  • "icefire" - 蓝色到橙色
  • "coolwarm" - 冷色到暖色
  • "Spectral" - 彩虹发散
sns.heatmap(correlation_matrix, cmap='vlag', center=0)
自定义调色板
# Create custom palette
custom = sns.color_palette("husl", 8)

# Light to dark gradient
palette = sns.light_palette("seagreen", as_cmap=True)

# Diverging palette from hues
palette = sns.diverging_palette(250, 10, as_cmap=True)

主题与美学

设置主题

set_theme() 控制整体外观:

# Set complete theme
sns.set_theme(style='whitegrid', palette='pastel', font='sans-serif')

# Reset to defaults
sns.set_theme()
样式

控制背景和网格外观:

  • "darkgrid" - 灰色背景配白色网格(默认)
  • "whitegrid" - 白色背景配灰色网格
  • "dark" - 灰色背景,无网格
  • "white" - 白色背景,无网格
  • "ticks" - 白色背景配坐标轴刻度
sns.set_style("whitegrid")

# Remove spines
sns.despine(left=False, bottom=False, offset=10, trim=True)

# Temporary style
with sns.axes_style("white"):
    sns.scatterplot(data=df, x='x', y='y')
上下文

为不同使用场景缩放元素:

  • "paper" - 最小(默认)
  • "notebook" - 稍大
  • "talk" - 演示幻灯片
  • "poster" - 大幅面
sns.set_context("talk", font_scale=1.2)

# Temporary context
with sns.plotting_context("poster"):
    sns.barplot(data=df, x='category', y='value')

最佳实践

1. 数据准备

始终使用结构良好的 DataFrame,并配有有意义的列名:

# Good: Named columns in DataFrame
df = pd.DataFrame({'bill': bills, 'tip': tips, 'day': days})
sns.scatterplot(data=df, x='bill', y='tip', hue='day')

# Avoid: Unnamed arrays
sns.scatterplot(x=x_array, y=y_array)  # Loses axis labels
2. 选择合适的绘图类型

连续 x,连续 y: scatterplot、lineplot、kdeplot、regplot 连续 x,分类 y: violinplot、boxplot、stripplot、swarmplot 单个连续变量: histplot、kdeplot、ecdfplot 相关性/矩阵: heatmap、clustermap 成对关系: pairplot、jointplot

3. 使用图形级函数进行分面
# Instead of manual subplot creation
sns.relplot(data=df, x='x', y='y', col='category', col_wrap=3)

# Not: Creating subplots manually for simple faceting
4. 利用语义映射

使用 hue、size 和 style 编码额外的维度:

sns.scatterplot(data=df, x='x', y='y',
                hue='category',      # Color by category
                size='importance',    # Size by continuous variable
                style='type')         # Marker style by type
5. 控制统计估计

许多函数会自动计算统计量。理解并自定义:

# Lineplot computes mean and 95% CI by default
sns.lineplot(data=df, x='time', y='value',
             errorbar='sd')  # Use standard deviation instead

# Barplot computes mean by default
sns.barplot(data=df, x='category', y='value',
            estimator='median',  # Use median instead
            errorbar=('ci', 95))  # Bootstrapped CI
6. 与 Matplotlib 结合使用

Seaborn 与 matplotlib 无缝集成,便于精细调整:

ax = sns.scatterplot(data=df, x='x', y='y')
ax.set(xlabel='Custom X Label', ylabel='Custom Y Label',
       title='Custom Title')
ax.axhline(y=0, color='r', linestyle='--')
plt.tight_layout()
7. 保存高质量图形
fig = sns.relplot(data=df, x='x', y='y', col='group')
fig.savefig('figure.png', dpi=300, bbox_inches='tight')
fig.savefig('figure.pdf')  # Vector format for publications

常见模式

探索性数据分析
# Quick overview of all relationships
sns.pairplot(data=df, hue='target', corner=True)

# Distribution exploration
sns.displot(data=df, x='variable', hue='group',
            kind='kde', fill=True, col='category')

# Correlation analysis
corr = df.corr()
sns.heatmap(corr, annot=True, cmap='coolwarm', center=0)
出版级图形
sns.set_theme(style='ticks', context='paper', font_scale=1.1)

g = sns.catplot(data=df, x='treatment', y='response',
                col='cell_line', kind='box', height=3, aspect=1.2)
g.set_axis_labels('Treatment Condition', 'Response (μM)')
g.set_titles('{col_name}')
sns.despine(trim=True)

g.savefig('figure.pdf', dpi=300, bbox_inches='tight')
复杂多面板图形
# Using matplotlib subplots with seaborn
fig, axes = plt.subplots(2, 2, figsize=(12, 10))

sns.scatterplot(data=df, x='x1', y='y', hue='group', ax=axes[0, 0])
sns.histplot(data=df, x='x1', hue='group', ax=axes[0, 1])
sns.violinplot(data=df, x='group', y='y', ax=axes[1, 0])
sns.heatmap(df.pivot_table(values='y', index='x1', columns='x2'),
            ax=axes[1, 1], cmap='viridis')

plt.tight_layout()
带置信带的时间序列
# Lineplot automatically aggregates and shows CI
sns.lineplot(data=timeseries, x='date', y='measurement',
             hue='sensor', style='location', errorbar='sd')

# For more control
g = sns.relplot(data=timeseries, x='date', y='measurement',
                col='location', hue='sensor', kind='line',
                height=4, aspect=1.5, errorbar=('ci', 95))
g.set_axis_labels('Date', 'Measurement (units)')

故障排除

问题:图例在绘图区域之外

图形级函数默认将图例放在外部。要移到内部:

g = sns.relplot(data=df, x='x', y='y', hue='category')
g._legend.set_bbox_to_anchor((0.9, 0.5))  # Adjust position
问题:标签重叠
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
问题:图形太小

对于图形级函数:

sns.relplot(data=df, x='x', y='y', height=6, aspect=1.5)

对于坐标轴级函数:

fig, ax = plt.subplots(figsize=(10, 6))
sns.scatterplot(data=df, x='x', y='y', ax=ax)
问题:颜色区分度不够
# Use a different palette
sns.set_palette("bright")

# Or specify number of colors
palette = sns.color_palette("husl", n_colors=len(df['category'].unique()))
sns.scatterplot(data=df, x='x', y='y', hue='category', palette=palette)
问题:KDE 过于平滑或锯齿状
# Adjust bandwidth
sns.kdeplot(data=df, x='x', bw_adjust=0.5)  # Less smooth
sns.kdeplot(data=df, x='x', bw_adjust=2)    # More smooth

资源

此技能包含参考资料,供深入探索:

references/
  • function_reference.md - 全面列出所有 seaborn 函数及其参数和示例
  • objects_interface.md - 现代 seaborn.objects API 的详细指南
  • examples.md - 针对不同分析场景的常见用例和代码模式

根据需要加载参考文件,以获取详细的函数签名、高级参数或具体示例。

评论

支持 Markdown