seaborn by davila7/claude-code-templates
npx skills add https://github.com/davila7/claude-code-templates --skill seabornSeaborn 是一个用于创建出版级质量统计图形的 Python 可视化库。使用此技能可以进行面向数据集的绘图、多变量分析、自动统计估计,以及用最少的代码创建复杂的多面板图形。
Seaborn 遵循以下核心原则:
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# 加载示例数据集
df = sns.load_dataset('tips')
# 创建简单可视化
sns.scatterplot(data=df, x='total_bill', y='tip', hue='day')
plt.show()
函数接口提供按可视化类型组织的专用绘图函数。每个类别都有 坐标轴级 函数(绘制到单个坐标轴)和 图形级 函数(通过分面管理整个图形)。
何时使用:
seaborn.objects 接口提供了一个类似于 ggplot2 的声明式、可组合 API。通过链式方法指定数据映射、标记、变换和比例来构建可视化。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
何时使用:
复杂的分层可视化
需要对变换进行细粒度控制时
构建自定义绘图类型
程序化绘图生成
from seaborn import objects as so
( 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 - 分面为多个子图(仅图形级)
sns.scatterplot(data=df, x='total_bill', y='tip', hue='time', size='size', style='sex')
sns.lineplot(data=timeseries, x='date', y='value', hue='category')
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"
sns.histplot(data=df, x='total_bill', hue='time', stat='density', multiple='stack')
sns.kdeplot(data=df, x='total_bill', y='tip', fill=True, levels=5, thresh=0.1)
sns.jointplot(data=df, x='total_bill', y='tip', kind='scatter', hue='time')
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"
sns.swarmplot(data=df, x='day', y='total_bill', hue='sex')
sns.violinplot(data=df, x='day', y='total_bill', hue='sex', split=True)
sns.barplot(data=df, x='day', y='total_bill', hue='sex', estimator='mean', errorbar='ci')
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 - 自定义散点和线属性
sns.regplot(data=df, x='total_bill', y='tip')
sns.lmplot(data=df, x='total_bill', y='tip', col='time', order=2, ci=95)
sns.residplot(data=df, x='total_bill', y='tip')
用于: 可视化矩阵、相关性和网格结构数据
heatmap() - 带注释的颜色编码矩阵clustermap() - 层次聚类的热图关键参数:
data - 2D 矩形数据集(DataFrame 或数组)
annot - 在单元格中显示值
fmt - 注释的格式字符串(例如 ".2f")
cmap - 颜色映射名称
center - 颜色映射中心的值(用于发散颜色映射)
vmin, vmax - 颜色比例限制
square - 强制方形单元格
linewidths - 单元格之间的间隙
corr = df.corr() sns.heatmap(corr, annot=True, fmt='.2f', cmap='coolwarm', center=0, square=True)
sns.clustermap(data, cmap='viridis', standard_scale=1, figsize=(10, 10))
Seaborn 提供网格对象用于创建复杂的多面板图形:
基于分类变量创建子图。当通过图形级函数(relplot、displot、catplot)调用时最有用,但也可直接用于自定义绘图。
g = sns.FacetGrid(df, col='time', row='sex', hue='smoker')
g.map(sns.scatterplot, 'total_bill', 'tip')
g.add_legend()
显示数据集中所有变量之间的成对关系。
g = sns.PairGrid(df, hue='species')
g.map_upper(sns.scatterplot)
g.map_lower(sns.kdeplot)
g.map_diag(sns.histplot)
g.add_legend()
将双变量图与边缘分布相结合。
g = sns.JointGrid(data=df, x='total_bill', y='tip')
g.plot_joint(sns.scatterplot)
g.plot_marginals(sns.histplot)
理解这一区别对于有效使用 seaborn 至关重要:
Axes 对象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何时使用:
分面可视化(小倍数)
快速探索性分析
一致的多面板布局
不需要与其他绘图类型组合
sns.relplot(data=df, x='x', y='y', col='category', row='group', hue='type', height=3, aspect=1.2)
每个变量是一列,每个观测值是一行。这种"整洁"格式提供了最大的灵活性:
# 长格式结构
subject condition measurement
0 1 control 10.5
1 1 treatment 12.3
2 2 control 9.8
3 2 treatment 13.1
优势:
变量分布在列中。适用于简单的矩形数据:
# 宽格式结构
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)
# 创建自定义调色板
custom = sns.color_palette("husl", 8)
# 从浅到深的渐变
palette = sns.light_palette("seagreen", as_cmap=True)
# 从色调创建发散调色板
palette = sns.diverging_palette(250, 10, as_cmap=True)
set_theme() 控制整体外观:
# 设置完整主题
sns.set_theme(style='whitegrid', palette='pastel', font='sans-serif')
# 重置为默认值
sns.set_theme()
控制背景和网格外观:
"darkgrid" - 带白色网格的灰色背景(默认)
"whitegrid" - 带灰色网格的白色背景
"dark" - 灰色背景,无网格
"white" - 白色背景,无网格
"ticks" - 带坐标轴刻度的白色背景
sns.set_style("whitegrid")
sns.despine(left=False, bottom=False, offset=10, trim=True)
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)
with sns.plotting_context("poster"): sns.barplot(data=df, x='category', y='value')
始终使用具有有意义列名的结构良好的 DataFrame:
# 良好:DataFrame 中的命名列
df = pd.DataFrame({'bill': bills, 'tip': tips, 'day': days})
sns.scatterplot(data=df, x='bill', y='tip', hue='day')
# 避免:未命名数组
sns.scatterplot(x=x_array, y=y_array) # 丢失坐标轴标签
连续 x,连续 y: scatterplot、lineplot、kdeplot、regplot 连续 x,分类 y: violinplot、boxplot、stripplot、swarmplot 一个连续变量: histplot、kdeplot、ecdfplot 相关性/矩阵: heatmap、clustermap 成对关系: pairplot、jointplot
# 而不是手动创建子图
sns.relplot(data=df, x='x', y='y', col='category', col_wrap=3)
# 不要:为简单分面手动创建子图
使用 hue、size 和 style 编码附加维度:
sns.scatterplot(data=df, x='x', y='y',
hue='category', # 按类别着色
size='importance', # 按连续变量调整大小
style='type') # 按类型调整标记样式
许多函数自动计算统计量。理解并自定义:
# Lineplot 默认计算均值和 95% CI
sns.lineplot(data=df, x='time', y='value',
errorbar='sd') # 改用标准差
# Barplot 默认计算均值
sns.barplot(data=df, x='category', y='value',
estimator='median', # 改用中位数
errorbar=('ci', 95)) # 自助法 CI
Seaborn 与 matplotlib 无缝集成,便于微调:
ax = sns.scatterplot(data=df, x='x', y='y')
ax.set(xlabel='自定义 X 标签', ylabel='自定义 Y 标签',
title='自定义标题')
ax.axhline(y=0, color='r', linestyle='--')
plt.tight_layout()
fig = sns.relplot(data=df, x='x', y='y', col='group')
fig.savefig('figure.png', dpi=300, bbox_inches='tight')
fig.savefig('figure.pdf') # 出版物用的矢量格式
# 快速概览所有关系
sns.pairplot(data=df, hue='target', corner=True)
# 分布探索
sns.displot(data=df, x='variable', hue='group',
kind='kde', fill=True, col='category')
# 相关性分析
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('处理条件', '响应 (μM)')
g.set_titles('{col_name}')
sns.despine(trim=True)
g.savefig('figure.pdf', dpi=300, bbox_inches='tight')
# 使用 matplotlib 子图与 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 自动聚合并显示 CI
sns.lineplot(data=timeseries, x='date', y='measurement',
hue='sensor', style='location', errorbar='sd')
# 更多控制
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('日期', '测量值 (单位)')
图形级函数默认将图例放在外部。要移动到内部:
g = sns.relplot(data=df, x='x', y='y', hue='category')
g._legend.set_bbox_to_anchor((0.9, 0.5)) # 调整位置
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)
# 使用不同的调色板
sns.set_palette("bright")
# 或指定颜色数量
palette = sns.color_palette("husl", n_colors=len(df['category'].unique()))
sns.scatterplot(data=df, x='x', y='y', hue='category', palette=palette)
# 调整带宽
sns.kdeplot(data=df, x='x', bw_adjust=0.5) # 更不平滑
sns.kdeplot(data=df, x='x', bw_adjust=2) # 更平滑
此技能包含用于深入探索的参考材料:
function_reference.md - 所有 seaborn 函数的全面列表,包含参数和示例objects_interface.md - 现代 seaborn.objects API 的详细指南examples.md - 不同分析场景的常见用例和代码模式根据需要加载参考文件以获取详细的函数签名、高级参数或特定示例。
每周安装次数
196
仓库
GitHub 星标数
22.6K
首次出现
2026年1月21日
安全审计
安装于
opencode155
claude-code150
gemini-cli146
codex140
cursor139
github-copilot124
Seaborn is a Python visualization library for creating publication-quality statistical graphics. Use this skill for dataset-oriented plotting, multivariate analysis, automatic statistical estimation, and complex multi-panel figures with minimal code.
Seaborn follows these core principles:
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()
The function interface provides specialized plotting functions organized by visualization type. Each category has axes-level functions (plot to single axes) and figure-level functions (manage entire figure with faceting).
When to use:
The seaborn.objects interface provides a declarative, composable API similar to ggplot2. Build visualizations by chaining methods to specify data mappings, marks, transformations, and scales.
When to use:
Complex layered visualizations
When you need fine-grained control over transformations
Building custom plot types
Programmatic plot generation
from seaborn import objects as so
( so.Plot(data=df, x='total_bill', y='tip') .add(so.Dot(), color='day') .add(so.Line(), so.PolyFit()) )
Use for: Exploring how two or more variables relate to each other
scatterplot() - Display individual observations as pointslineplot() - Show trends and changes (automatically aggregates and computes CI)relplot() - Figure-level interface with automatic facetingKey parameters:
x, y - Primary variables
hue - Color encoding for additional categorical/continuous variable
size - Point/line size encoding
style - Marker/line style encoding
col, row - Facet into multiple subplots (figure-level only)
sns.scatterplot(data=df, x='total_bill', y='tip', hue='time', size='size', style='sex')
sns.lineplot(data=timeseries, x='date', y='value', hue='category')
sns.relplot(data=df, x='total_bill', y='tip', col='time', row='sex', hue='smoker', kind='scatter')
Use for: Understanding data spread, shape, and probability density
histplot() - Bar-based frequency distributions with flexible binningkdeplot() - Smooth density estimates using Gaussian kernelsecdfplot() - Empirical cumulative distribution (no parameters to tune)rugplot() - Individual observation tick marksdisplot() - Figure-level interface for univariate and bivariate distributionsjointplot() - Bivariate plot with marginal distributionspairplot() - Matrix of pairwise relationships across datasetKey parameters:
x, y - Variables (y optional for univariate)
hue - Separate distributions by category
stat - Normalization: "count", "frequency", "probability", "density"
bins / binwidth - Histogram binning control
bw_adjust - KDE bandwidth multiplier (higher = smoother)
fill - Fill area under curve
multiple - How to handle hue: "layer", "stack", "dodge", "fill"
Use for: Comparing distributions or statistics across discrete categories
Categorical scatterplots:
stripplot() - Points with jitter to show all observationsswarmplot() - Non-overlapping points (beeswarm algorithm)Distribution comparisons:
boxplot() - Quartiles and outliersviolinplot() - KDE + quartile informationboxenplot() - Enhanced boxplot for larger datasetsStatistical estimates:
barplot() - Mean/aggregate with confidence intervalspointplot() - Point estimates with connecting linescountplot() - Count of observations per categoryFigure-level:
catplot() - Faceted categorical plots (set kind parameter)Key parameters:
x, y - Variables (one typically categorical)
hue - Additional categorical grouping
order, hue_order - Control category ordering
dodge - Separate hue levels side-by-side
orient - "v" (vertical) or "h" (horizontal)
kind - Plot type for catplot: "strip", "swarm", "box", "violin", "bar", "point"
sns.swarmplot(data=df, x='day', y='total_bill', hue='sex')
Use for: Visualizing linear regressions and residuals
regplot() - Axes-level regression plot with scatter + fit linelmplot() - Figure-level with faceting supportresidplot() - Residual plot for assessing model fitKey parameters:
x, y - Variables to regress
order - Polynomial regression order
logistic - Fit logistic regression
robust - Use robust regression (less sensitive to outliers)
ci - Confidence interval width (default 95)
scatter_kws, line_kws - Customize scatter and line properties
sns.regplot(data=df, x='total_bill', y='tip')
Use for: Visualizing matrices, correlations, and grid-structured data
heatmap() - Color-encoded matrix with annotationsclustermap() - Hierarchically-clustered heatmapKey parameters:
data - 2D rectangular dataset (DataFrame or array)
annot - Display values in cells
fmt - Format string for annotations (e.g., ".2f")
cmap - Colormap name
center - Value at colormap center (for diverging colormaps)
vmin, vmax - Color scale limits
square - Force square cells
linewidths - Gap between cells
Seaborn provides grid objects for creating complex multi-panel figures:
Create subplots based on categorical variables. Most useful when called through figure-level functions (relplot, displot, catplot), but can be used directly for custom plots.
g = sns.FacetGrid(df, col='time', row='sex', hue='smoker')
g.map(sns.scatterplot, 'total_bill', 'tip')
g.add_legend()
Show pairwise relationships between all variables in a dataset.
g = sns.PairGrid(df, hue='species')
g.map_upper(sns.scatterplot)
g.map_lower(sns.kdeplot)
g.map_diag(sns.histplot)
g.add_legend()
Combine bivariate plot with marginal distributions.
g = sns.JointGrid(data=df, x='total_bill', y='tip')
g.plot_joint(sns.scatterplot)
g.plot_marginals(sns.histplot)
Understanding this distinction is crucial for effective seaborn usage:
Axes objectax= parameter for precise placementAxes objectscatterplot, histplot, boxplot, regplot, heatmapWhen to use:
Building custom multi-plot layouts
Combining different plot types
Need matplotlib-level control
Integrating with existing matplotlib code
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 and row parametersFacetGrid, JointGrid, or PairGrid objectsheight and aspect for sizing (per subplot)relplot, displot, catplot, lmplot, , When to use:
Faceted visualizations (small multiples)
Quick exploratory analysis
Consistent multi-panel layouts
Don't need to combine with other plot types
sns.relplot(data=df, x='x', y='y', col='category', row='group', hue='type', height=3, aspect=1.2)
Each variable is a column, each observation is a row. This "tidy" format provides maximum flexibility:
# 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
Advantages:
Variables are spread across columns. Useful for simple rectangular data:
# Wide-form structure
control treatment
0 10.5 12.3
1 9.8 13.1
Use cases:
Converting wide to long:
df_long = df.melt(var_name='condition', value_name='measurement')
Seaborn provides carefully designed color palettes for different data types:
Distinguish categories through hue variation:
"deep" - Default, vivid colors
"muted" - Softer, less saturated
"pastel" - Light, desaturated
"bright" - Highly saturated
"dark" - Dark values
"colorblind" - Safe for color vision deficiency
sns.set_palette("colorblind") sns.color_palette("Set2")
Show progression from low to high values:
"rocket", "mako" - Wide luminance range (good for heatmaps)
"flare", "crest" - Restricted luminance (good for points/lines)
"viridis", "magma", "plasma" - Matplotlib perceptually uniform
sns.heatmap(data, cmap='rocket') sns.kdeplot(data=df, x='x', y='y', cmap='mako', fill=True)
Emphasize deviations from a midpoint:
"vlag" - Blue to red
"icefire" - Blue to orange
"coolwarm" - Cool to warm
"Spectral" - Rainbow diverging
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() controls overall appearance:
# Set complete theme
sns.set_theme(style='whitegrid', palette='pastel', font='sans-serif')
# Reset to defaults
sns.set_theme()
Control background and grid appearance:
"darkgrid" - Gray background with white grid (default)
"whitegrid" - White background with gray grid
"dark" - Gray background, no grid
"white" - White background, no grid
"ticks" - White background with axis ticks
sns.set_style("whitegrid")
sns.despine(left=False, bottom=False, offset=10, trim=True)
with sns.axes_style("white"): sns.scatterplot(data=df, x='x', y='y')
Scale elements for different use cases:
"paper" - Smallest (default)
"notebook" - Slightly larger
"talk" - Presentation slides
"poster" - Large format
sns.set_context("talk", font_scale=1.2)
with sns.plotting_context("poster"): sns.barplot(data=df, x='category', y='value')
Always use well-structured DataFrames with meaningful column names:
# 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
Continuous x, continuous y: scatterplot, lineplot, kdeplot, regplot Continuous x, categorical y: violinplot, boxplot, stripplot, swarmplot One continuous variable: histplot, kdeplot, ecdfplot , ,
# 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
Use hue, size, and style to encode additional dimensions:
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
Many functions compute statistics automatically. Understand and customize:
# 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
Seaborn integrates seamlessly with matplotlib for fine-tuning:
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()
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)')
Figure-level functions place legends outside by default. To move inside:
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()
For figure-level functions:
sns.relplot(data=df, x='x', y='y', height=6, aspect=1.5)
For axes-level functions:
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)
# 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
This skill includes reference materials for deeper exploration:
function_reference.md - Comprehensive listing of all seaborn functions with parameters and examplesobjects_interface.md - Detailed guide to the modern seaborn.objects APIexamples.md - Common use cases and code patterns for different analysis scenariosLoad reference files as needed for detailed function signatures, advanced parameters, or specific examples.
Weekly Installs
196
Repository
GitHub Stars
22.6K
First Seen
Jan 21, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode155
claude-code150
gemini-cli146
codex140
cursor139
github-copilot124
DOCX文件创建、编辑与分析完整指南 - 使用docx-js、Pandoc和Python脚本
43,600 周安装
sns.histplot(data=df, x='total_bill', hue='time', stat='density', multiple='stack')
sns.kdeplot(data=df, x='total_bill', y='tip', fill=True, levels=5, thresh=0.1)
sns.jointplot(data=df, x='total_bill', y='tip', kind='scatter', hue='time')
sns.pairplot(data=df, hue='species', corner=True)
sns.violinplot(data=df, x='day', y='total_bill', hue='sex', split=True)
sns.barplot(data=df, x='day', y='total_bill', hue='sex', estimator='mean', errorbar='ci')
sns.catplot(data=df, x='day', y='total_bill', col='time', kind='box')
sns.lmplot(data=df, x='total_bill', y='tip', col='time', order=2, ci=95)
sns.residplot(data=df, x='total_bill', y='tip')
corr = df.corr() sns.heatmap(corr, annot=True, fmt='.2f', cmap='coolwarm', center=0, square=True)
sns.clustermap(data, cmap='viridis', standard_scale=1, figsize=(10, 10))
jointplotpairplotheatmapclustermappairplotjointplot