
Seaborn
- 37 installs
- 16 repo stars
- Updated November 20, 2025
- jackspace/claudeskillz
Create statistical visualizations with Seaborn: scatter, box, violin, heatmaps, pair plots, and regression figures.
About
Seaborn is a Python library for statistical data visualization. Developers use it for exploratory analysis and publication figures like heatmaps, distributions, and faceted plots.
- Scatter, box, violin, heatmap, and pair-plot chart types
- Regression, correlation matrices, KDE, and faceted plots
Seaborn by the numbers
- 37 all-time installs (skills.sh)
- Ranked #1,029 of 2,065 Data Science & ML skills by installs in the Skillselion catalog
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/jackspace/claudeskillz --skill seabornAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 37 |
|---|---|
| repo stars | ★ 16 |
| Last updated | November 20, 2025 |
| Repository | jackspace/claudeskillz ↗ |
What it does
Create statistical visualizations with Seaborn: scatter, box, violin, heatmaps, pair plots, and regression figures.
Files
Seaborn Statistical Visualization
Overview
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.
Design Philosophy
Seaborn follows these core principles:
1. Dataset-oriented: Work directly with DataFrames and named variables rather than abstract coordinates 2. Semantic mapping: Automatically translate data values into visual properties (colors, sizes, styles) 3. Statistical awareness: Built-in aggregation, error estimation, and confidence intervals 4. Aesthetic defaults: Publication-ready themes and color palettes out of the box 5. Matplotlib integration: Full compatibility with matplotlib customization when needed
Quick Start
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()Core Plotting Interfaces
Function Interface (Traditional)
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:
- Quick exploratory analysis
- Single-purpose visualizations
- When you need a specific plot type
Objects Interface (Modern)
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
# Declarative syntax
(
so.Plot(data=df, x='total_bill', y='tip')
.add(so.Dot(), color='day')
.add(so.Line(), so.PolyFit())
)Plotting Functions by Category
Relational Plots (Relationships Between Variables)
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 faceting
Key parameters:
x,y- Primary variableshue- Color encoding for additional categorical/continuous variablesize- Point/line size encodingstyle- Marker/line style encodingcol,row- Facet into multiple subplots (figure-level only)
# 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')Distribution Plots (Single and Bivariate Distributions)
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 dataset
Key parameters:
x,y- Variables (y optional for univariate)hue- Separate distributions by categorystat- Normalization: "count", "frequency", "probability", "density"bins/binwidth- Histogram binning controlbw_adjust- KDE bandwidth multiplier (higher = smoother)fill- Fill area under curvemultiple- How to handle 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)Categorical Plots (Comparisons Across Categories)
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 datasets
Statistical estimates:
barplot()- Mean/aggregate with confidence intervalspointplot()- Point estimates with connecting linescountplot()- Count of observations per category
Figure-level:
catplot()- Faceted categorical plots (setkindparameter)
Key parameters:
x,y- Variables (one typically categorical)hue- Additional categorical groupingorder,hue_order- Control category orderingdodge- Separate hue levels side-by-sideorient- "v" (vertical) or "h" (horizontal)kind- Plot type for 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')Regression Plots (Linear Relationships)
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 fit
Key parameters:
x,y- Variables to regressorder- Polynomial regression orderlogistic- Fit logistic regressionrobust- Use robust regression (less sensitive to outliers)ci- Confidence interval width (default 95)scatter_kws,line_kws- Customize scatter and line properties
# 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')Matrix Plots (Rectangular Data)
Use for: Visualizing matrices, correlations, and grid-structured data
heatmap()- Color-encoded matrix with annotationsclustermap()- Hierarchically-clustered heatmap
Key parameters:
data- 2D rectangular dataset (DataFrame or array)annot- Display values in cellsfmt- Format string for annotations (e.g., ".2f")cmap- Colormap namecenter- Value at colormap center (for diverging colormaps)vmin,vmax- Color scale limitssquare- Force square cellslinewidths- Gap between cells
# 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))Multi-Plot Grids
Seaborn provides grid objects for creating complex multi-panel figures:
FacetGrid
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()PairGrid
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()JointGrid
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)Figure-Level vs Axes-Level Functions
Understanding this distinction is crucial for effective seaborn usage:
Axes-Level Functions
- Plot to a single matplotlib
Axesobject - Integrate easily into complex matplotlib figures
- Accept
ax=parameter for precise placement - Return
Axesobject - Examples:
scatterplot,histplot,boxplot,regplot,heatmap
When 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])Figure-Level Functions
- Manage entire figure including all subplots
- Built-in faceting via
colandrowparameters - Return
FacetGrid,JointGrid, orPairGridobjects - Use
heightandaspectfor sizing (per subplot) - Cannot be placed in existing figure
- Examples:
relplot,displot,catplot,lmplot,jointplot,pairplot
When to use:
- Faceted visualizations (small multiples)
- Quick exploratory analysis
- Consistent multi-panel layouts
- Don't need to combine with other plot types
# Automatic faceting
sns.relplot(data=df, x='x', y='y', col='category', row='group',
hue='type', height=3, aspect=1.2)Data Structure Requirements
Long-Form Data (Preferred)
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.1Advantages:
- Works with all seaborn functions
- Easy to remap variables to visual properties
- Supports arbitrary complexity
- Natural for DataFrame operations
Wide-Form Data
Variables are spread across columns. Useful for simple rectangular data:
# Wide-form structure
control treatment
0 10.5 12.3
1 9.8 13.1Use cases:
- Simple time series
- Correlation matrices
- Heatmaps
- Quick plots of array data
Converting wide to long:
df_long = df.melt(var_name='condition', value_name='measurement')Color Palettes
Seaborn provides carefully designed color palettes for different data types:
Qualitative Palettes (Categorical Data)
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")Sequential Palettes (Ordered Data)
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)Diverging Palettes (Centered Data)
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)Custom Palettes
# 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)Theming and Aesthetics
Set Theme
set_theme() controls overall appearance:
# Set complete theme
sns.set_theme(style='whitegrid', palette='pastel', font='sans-serif')
# Reset to defaults
sns.set_theme()Styles
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")
# 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')Contexts
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)
# Temporary context
with sns.plotting_context("poster"):
sns.barplot(data=df, x='category', y='value')Best Practices
1. Data Preparation
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 labels2. Choose the Right Plot Type
Continuous x, continuous y: scatterplot, lineplot, kdeplot, regplot Continuous x, categorical y: violinplot, boxplot, stripplot, swarmplot One continuous variable: histplot, kdeplot, ecdfplot Correlations/matrices: heatmap, clustermap Pairwise relationships: pairplot, jointplot
3. Use Figure-Level Functions for Faceting
# Instead of manual subplot creation
sns.relplot(data=df, x='x', y='y', col='category', col_wrap=3)
# Not: Creating subplots manually for simple faceting4. Leverage Semantic Mappings
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 type5. Control Statistical Estimation
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 CI6. Combine with Matplotlib
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()7. Save High-Quality Figures
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 publicationsCommon Patterns
Exploratory Data Analysis
# 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)Publication-Quality Figures
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')Complex Multi-Panel Figures
# 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()Time Series with Confidence Bands
# 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)')Troubleshooting
Issue: Legend Outside Plot Area
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 positionIssue: Overlapping Labels
plt.xticks(rotation=45, ha='right')
plt.tight_layout()Issue: Figure Too Small
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)Issue: Colors Not Distinct Enough
# 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)Issue: KDE Too Smooth or Jagged
# Adjust bandwidth
sns.kdeplot(data=df, x='x', bw_adjust=0.5) # Less smooth
sns.kdeplot(data=df, x='x', bw_adjust=2) # More smoothResources
This skill includes reference materials for deeper exploration:
references/
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 scenarios
Load reference files as needed for detailed function signatures, advanced parameters, or specific examples.
{
"description": "\"Statistical visualization. Scatter, box, violin, heatmaps, pair plots, regression, correlation matrices, KDE, faceted plots, for exploratory analysis and publication figures.\"",
"references": {
"files": [
"references/examples.md",
"references/function_reference.md",
"references/objects_interface.md"
]
},
"content": "```python\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\ndf = sns.load_dataset('tips')\r\n\r\n\r\n### Function Interface (Traditional)\r\n\r\nThe 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).\r\n\r\n**When to use:**\r\n- Quick exploratory analysis\r\n- Single-purpose visualizations\r\n- When you need a specific plot type\r\n\r\n### Objects Interface (Modern)\r\n\r\nThe `seaborn.objects` interface provides a declarative, composable API similar to ggplot2. Build visualizations by chaining methods to specify data mappings, marks, transformations, and scales.\r\n\r\n**When to use:**\r\n- Complex layered visualizations\r\n- When you need fine-grained control over transformations\r\n- Building custom plot types\r\n- Programmatic plot generation\r\n\r\n```python\r\nfrom seaborn import objects as so\r\n\r\n\r\n### Relational Plots (Relationships Between Variables)\r\n\r\n**Use for:** Exploring how two or more variables relate to each other\r\n\r\n- `scatterplot()` - Display individual observations as points\r\n- `lineplot()` - Show trends and changes (automatically aggregates and computes CI)\r\n- `relplot()` - Figure-level interface with automatic faceting\r\n\r\n**Key parameters:**\r\n- `x`, `y` - Primary variables\r\n- `hue` - Color encoding for additional categorical/continuous variable\r\n- `size` - Point/line size encoding\r\n- `style` - Marker/line style encoding\r\n- `col`, `row` - Facet into multiple subplots (figure-level only)\r\n\r\n```python\r\nsns.scatterplot(data=df, x='total_bill', y='tip',\r\n hue='time', size='size', style='sex')\r\n\r\nsns.lineplot(data=timeseries, x='date', y='value', hue='category')\r\n\r\nsns.relplot(data=df, x='total_bill', y='tip',\r\n col='time', row='sex', hue='smoker', kind='scatter')\r\n```\r\n\r\n### Distribution Plots (Single and Bivariate Distributions)\r\n\r\n**Use for:** Understanding data spread, shape, and probability density\r\n\r\n- `histplot()` - Bar-based frequency distributions with flexible binning\r\n- `kdeplot()` - Smooth density estimates using Gaussian kernels\r\n- `ecdfplot()` - Empirical cumulative distribution (no parameters to tune)\r\n- `rugplot()` - Individual observation tick marks\r\n- `displot()` - Figure-level interface for univariate and bivariate distributions\r\n- `jointplot()` - Bivariate plot with marginal distributions\r\n- `pairplot()` - Matrix of pairwise relationships across dataset\r\n\r\n**Key parameters:**\r\n- `x`, `y` - Variables (y optional for univariate)\r\n- `hue` - Separate distributions by category\r\n- `stat` - Normalization: \"count\", \"frequency\", \"probability\", \"density\"\r\n- `bins` / `binwidth` - Histogram binning control\r\n- `bw_adjust` - KDE bandwidth multiplier (higher = smoother)\r\n- `fill` - Fill area under curve\r\n- `multiple` - How to handle hue: \"layer\", \"stack\", \"dodge\", \"fill\"\r\n\r\n```python\r\nsns.histplot(data=df, x='total_bill', hue='time',\r\n stat='density', multiple='stack')\r\n\r\nsns.kdeplot(data=df, x='total_bill', y='tip',\r\n fill=True, levels=5, thresh=0.1)\r\n\r\nsns.jointplot(data=df, x='total_bill', y='tip',\r\n kind='scatter', hue='time')\r\n\r\nsns.pairplot(data=df, hue='species', corner=True)\r\n```\r\n\r\n### Categorical Plots (Comparisons Across Categories)\r\n\r\n**Use for:** Comparing distributions or statistics across discrete categories\r\n\r\n**Categorical scatterplots:**\r\n- `stripplot()` - Points with jitter to show all observations\r\n- `swarmplot()` - Non-overlapping points (beeswarm algorithm)\r\n\r\n**Distribution comparisons:**\r\n- `boxplot()` - Quartiles and outliers\r\n- `violinplot()` - KDE + quartile information\r\n- `boxenplot()` - Enhanced boxplot for larger datasets\r\n\r\n**Statistical estimates:**\r\n- `barplot()` - Mean/aggregate with confidence intervals\r\n- `pointplot()` - Point estimates with connecting lines\r\n- `countplot()` - Count of observations per category\r\n\r\n**Figure-level:**\r\n- `catplot()` - Faceted categorical plots (set `kind` parameter)\r\n\r\n**Key parameters:**\r\n- `x`, `y` - Variables (one typically categorical)\r\n- `hue` - Additional categorical grouping\r\n- `order`, `hue_order` - Control category ordering\r\n- `dodge` - Separate hue levels side-by-side\r\n- `orient` - \"v\" (vertical) or \"h\" (horizontal)\r\n- `kind` - Plot type for catplot: \"strip\", \"swarm\", \"box\", \"violin\", \"bar\", \"point\"\r\n\r\n```python\r\nsns.swarmplot(data=df, x='day', y='total_bill', hue='sex')\r\n\r\nsns.violinplot(data=df, x='day', y='total_bill',\r\n hue='sex', split=True)\r\n\r\nsns.barplot(data=df, x='day', y='total_bill',\r\n hue='sex', estimator='mean', errorbar='ci')\r\n\r\nsns.catplot(data=df, x='day', y='total_bill',\r\n col='time', kind='box')\r\n```\r\n\r\n### Regression Plots (Linear Relationships)\r\n\r\n**Use for:** Visualizing linear regressions and residuals\r\n\r\n- `regplot()` - Axes-level regression plot with scatter + fit line\r\n- `lmplot()` - Figure-level with faceting support\r\n- `residplot()` - Residual plot for assessing model fit\r\n\r\n**Key parameters:**\r\n- `x`, `y` - Variables to regress\r\n- `order` - Polynomial regression order\r\n- `logistic` - Fit logistic regression\r\n- `robust` - Use robust regression (less sensitive to outliers)\r\n- `ci` - Confidence interval width (default 95)\r\n- `scatter_kws`, `line_kws` - Customize scatter and line properties\r\n\r\n```python\r\nsns.regplot(data=df, x='total_bill', y='tip')\r\n\r\nsns.lmplot(data=df, x='total_bill', y='tip',\r\n col='time', order=2, ci=95)\r\n\r\nsns.residplot(data=df, x='total_bill', y='tip')\r\n```\r\n\r\n### Matrix Plots (Rectangular Data)\r\n\r\n**Use for:** Visualizing matrices, correlations, and grid-structured data\r\n\r\n- `heatmap()` - Color-encoded matrix with annotations\r\n- `clustermap()` - Hierarchically-clustered heatmap\r\n\r\n**Key parameters:**\r\n- `data` - 2D rectangular dataset (DataFrame or array)\r\n- `annot` - Display values in cells\r\n- `fmt` - Format string for annotations (e.g., \".2f\")\r\n- `cmap` - Colormap name\r\n- `center` - Value at colormap center (for diverging colormaps)\r\n- `vmin`, `vmax` - Color scale limits\r\n- `square` - Force square cells\r\n- `linewidths` - Gap between cells\r\n\r\n```python\r\ncorr = df.corr()\r\nsns.heatmap(corr, annot=True, fmt='.2f',\r\n cmap='coolwarm', center=0, square=True)\r\n\r\n\r\nUnderstanding this distinction is crucial for effective seaborn usage:\r\n\r\n### Axes-Level Functions\r\n- Plot to a single matplotlib `Axes` object\r\n- Integrate easily into complex matplotlib figures\r\n- Accept `ax=` parameter for precise placement\r\n- Return `Axes` object\r\n- Examples: `scatterplot`, `histplot`, `boxplot`, `regplot`, `heatmap`\r\n\r\n**When to use:**\r\n- Building custom multi-plot layouts\r\n- Combining different plot types\r\n- Need matplotlib-level control\r\n- Integrating with existing matplotlib code\r\n\r\n```python\r\nfig, axes = plt.subplots(2, 2, figsize=(10, 10))\r\nsns.scatterplot(data=df, x='x', y='y', ax=axes[0, 0])\r\nsns.histplot(data=df, x='x', ax=axes[0, 1])\r\nsns.boxplot(data=df, x='cat', y='y', ax=axes[1, 0])\r\nsns.kdeplot(data=df, x='x', y='y', ax=axes[1, 1])\r\n```\r\n\r\n### Figure-Level Functions\r\n- Manage entire figure including all subplots\r\n- Built-in faceting via `col` and `row` parameters\r\n- Return `FacetGrid`, `JointGrid`, or `PairGrid` objects\r\n- Use `height` and `aspect` for sizing (per subplot)\r\n- Cannot be placed in existing figure\r\n- Examples: `relplot`, `displot`, `catplot`, `lmplot`, `jointplot`, `pairplot`\r\n\r\n**When to use:**\r\n- Faceted visualizations (small multiples)\r\n- Quick exploratory analysis\r\n- Consistent multi-panel layouts\r\n- Don't need to combine with other plot types\r\n\r\n```python\r\n\r\n### Long-Form Data (Preferred)\r\n\r\nEach variable is a column, each observation is a row. This \"tidy\" format provides maximum flexibility:\r\n\r\n```python\r\n subject condition measurement\r\n0 1 control 10.5\r\n1 1 treatment 12.3\r\n2 2 control 9.8\r\n3 2 treatment 13.1\r\n```\r\n\r\n**Advantages:**\r\n- Works with all seaborn functions\r\n- Easy to remap variables to visual properties\r\n- Supports arbitrary complexity\r\n- Natural for DataFrame operations\r\n\r\n### Wide-Form Data\r\n\r\nVariables are spread across columns. Useful for simple rectangular data:\r\n\r\n```python\r\n\r\nSeaborn provides carefully designed color palettes for different data types:\r\n\r\n### Qualitative Palettes (Categorical Data)\r\n\r\nDistinguish categories through hue variation:\r\n- `\"deep\"` - Default, vivid colors\r\n- `\"muted\"` - Softer, less saturated\r\n- `\"pastel\"` - Light, desaturated\r\n- `\"bright\"` - Highly saturated\r\n- `\"dark\"` - Dark values\r\n- `\"colorblind\"` - Safe for color vision deficiency\r\n\r\n```python\r\nsns.set_palette(\"colorblind\")\r\nsns.color_palette(\"Set2\")\r\n```\r\n\r\n### Sequential Palettes (Ordered Data)\r\n\r\nShow progression from low to high values:\r\n- `\"rocket\"`, `\"mako\"` - Wide luminance range (good for heatmaps)\r\n- `\"flare\"`, `\"crest\"` - Restricted luminance (good for points/lines)\r\n- `\"viridis\"`, `\"magma\"`, `\"plasma\"` - Matplotlib perceptually uniform\r\n\r\n```python\r\nsns.heatmap(data, cmap='rocket')\r\nsns.kdeplot(data=df, x='x', y='y', cmap='mako', fill=True)\r\n```\r\n\r\n### Diverging Palettes (Centered Data)\r\n\r\nEmphasize deviations from a midpoint:\r\n- `\"vlag\"` - Blue to red\r\n- `\"icefire\"` - Blue to orange\r\n- `\"coolwarm\"` - Cool to warm\r\n- `\"Spectral\"` - Rainbow diverging\r\n\r\n```python\r\nsns.heatmap(correlation_matrix, cmap='vlag', center=0)\r\n```\r\n\r\n### Custom Palettes\r\n\r\n```python\r\ncustom = sns.color_palette(\"husl\", 8)\r\n\r\npalette = sns.light_palette(\"seagreen\", as_cmap=True)\r\n\r\n\r\n### Set Theme\r\n\r\n`set_theme()` controls overall appearance:\r\n\r\n```python\r\nsns.set_theme(style='whitegrid', palette='pastel', font='sans-serif')\r\n\r\nsns.set_theme()\r\n```\r\n\r\n### Styles\r\n\r\nControl background and grid appearance:\r\n- `\"darkgrid\"` - Gray background with white grid (default)\r\n- `\"whitegrid\"` - White background with gray grid\r\n- `\"dark\"` - Gray background, no grid\r\n- `\"white\"` - White background, no grid\r\n- `\"ticks\"` - White background with axis ticks\r\n\r\n```python\r\nsns.set_style(\"whitegrid\")\r\n\r\nsns.despine(left=False, bottom=False, offset=10, trim=True)\r\n\r\nwith sns.axes_style(\"white\"):\r\n sns.scatterplot(data=df, x='x', y='y')\r\n```\r\n\r\n### Contexts\r\n\r\nScale elements for different use cases:\r\n- `\"paper\"` - Smallest (default)\r\n- `\"notebook\"` - Slightly larger\r\n- `\"talk\"` - Presentation slides\r\n- `\"poster\"` - Large format\r\n\r\n```python\r\nsns.set_context(\"talk\", font_scale=1.2)\r\n\r\n\r\n### 1. Data Preparation\r\n\r\nAlways use well-structured DataFrames with meaningful column names:\r\n\r\n```python\r\ndf = pd.DataFrame({'bill': bills, 'tip': tips, 'day': days})\r\nsns.scatterplot(data=df, x='bill', y='tip', hue='day')\r\n\r\nsns.scatterplot(x=x_array, y=y_array) # Loses axis labels\r\n```\r\n\r\n### 2. Choose the Right Plot Type\r\n\r\n**Continuous x, continuous y:** `scatterplot`, `lineplot`, `kdeplot`, `regplot`\r\n**Continuous x, categorical y:** `violinplot`, `boxplot`, `stripplot`, `swarmplot`\r\n**One continuous variable:** `histplot`, `kdeplot`, `ecdfplot`\r\n**Correlations/matrices:** `heatmap`, `clustermap`\r\n**Pairwise relationships:** `pairplot`, `jointplot`\r\n\r\n### 3. Use Figure-Level Functions for Faceting\r\n\r\n```python\r\nsns.relplot(data=df, x='x', y='y', col='category', col_wrap=3)\r\n\r\n```\r\n\r\n### 4. Leverage Semantic Mappings\r\n\r\nUse `hue`, `size`, and `style` to encode additional dimensions:\r\n\r\n```python\r\nsns.scatterplot(data=df, x='x', y='y',\r\n hue='category', # Color by category\r\n size='importance', # Size by continuous variable\r\n style='type') # Marker style by type\r\n```\r\n\r\n### 5. Control Statistical Estimation\r\n\r\nMany functions compute statistics automatically. Understand and customize:\r\n\r\n```python\r\nsns.lineplot(data=df, x='time', y='value',\r\n errorbar='sd') # Use standard deviation instead\r\n\r\n\r\n### Exploratory Data Analysis\r\n\r\n```python\r\nsns.pairplot(data=df, hue='target', corner=True)\r\n\r\nsns.displot(data=df, x='variable', hue='group',\r\n kind='kde', fill=True, col='category')\r\n\r\ncorr = df.corr()\r\nsns.heatmap(corr, annot=True, cmap='coolwarm', center=0)\r\n```\r\n\r\n### Publication-Quality Figures\r\n\r\n```python\r\nsns.set_theme(style='ticks', context='paper', font_scale=1.1)\r\n\r\ng = sns.catplot(data=df, x='treatment', y='response',\r\n col='cell_line', kind='box', height=3, aspect=1.2)\r\ng.set_axis_labels('Treatment Condition', 'Response (μM)')\r\ng.set_titles('{col_name}')\r\nsns.despine(trim=True)\r\n\r\ng.savefig('figure.pdf', dpi=300, bbox_inches='tight')\r\n```\r\n\r\n### Complex Multi-Panel Figures\r\n\r\n```python\r\nfig, axes = plt.subplots(2, 2, figsize=(12, 10))\r\n\r\nsns.scatterplot(data=df, x='x1', y='y', hue='group', ax=axes[0, 0])\r\nsns.histplot(data=df, x='x1', hue='group', ax=axes[0, 1])\r\nsns.violinplot(data=df, x='group', y='y', ax=axes[1, 0])\r\nsns.heatmap(df.pivot_table(values='y', index='x1', columns='x2'),\r\n ax=axes[1, 1], cmap='viridis')\r\n\r\nplt.tight_layout()\r\n```\r\n\r\n### Time Series with Confidence Bands\r\n\r\n```python\r\nsns.lineplot(data=timeseries, x='date', y='measurement',\r\n hue='sensor', style='location', errorbar='sd')\r\n\r\n\r\n### Issue: Legend Outside Plot Area\r\n\r\nFigure-level functions place legends outside by default. To move inside:\r\n\r\n```python\r\ng = sns.relplot(data=df, x='x', y='y', hue='category')\r\ng._legend.set_bbox_to_anchor((0.9, 0.5)) # Adjust position\r\n```\r\n\r\n### Issue: Overlapping Labels\r\n\r\n```python\r\nplt.xticks(rotation=45, ha='right')\r\nplt.tight_layout()\r\n```\r\n\r\n### Issue: Figure Too Small\r\n\r\nFor figure-level functions:\r\n```python\r\nsns.relplot(data=df, x='x', y='y', height=6, aspect=1.5)\r\n```\r\n\r\nFor axes-level functions:\r\n```python\r\nfig, ax = plt.subplots(figsize=(10, 6))\r\nsns.scatterplot(data=df, x='x', y='y', ax=ax)\r\n```\r\n\r\n### Issue: Colors Not Distinct Enough\r\n\r\n```python\r\nsns.set_palette(\"bright\")\r\n\r\npalette = sns.color_palette(\"husl\", n_colors=len(df['category'].unique()))\r\nsns.scatterplot(data=df, x='x', y='y', hue='category', palette=palette)\r\n```\r\n\r\n### Issue: KDE Too Smooth or Jagged\r\n\r\n```python",
"name": "seaborn",
"id": "scientific-pkg-seaborn",
"sections": {
"Overview": "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.",
"Theming and Aesthetics": "with sns.plotting_context(\"poster\"):\r\n sns.barplot(data=df, x='category', y='value')\r\n```",
"Multi-Plot Grids": "Seaborn provides grid objects for creating complex multi-panel figures:\r\n\r\n### FacetGrid\r\n\r\nCreate subplots based on categorical variables. Most useful when called through figure-level functions (`relplot`, `displot`, `catplot`), but can be used directly for custom plots.\r\n\r\n```python\r\ng = sns.FacetGrid(df, col='time', row='sex', hue='smoker')\r\ng.map(sns.scatterplot, 'total_bill', 'tip')\r\ng.add_legend()\r\n```\r\n\r\n### PairGrid\r\n\r\nShow pairwise relationships between all variables in a dataset.\r\n\r\n```python\r\ng = sns.PairGrid(df, hue='species')\r\ng.map_upper(sns.scatterplot)\r\ng.map_lower(sns.kdeplot)\r\ng.map_diag(sns.histplot)\r\ng.add_legend()\r\n```\r\n\r\n### JointGrid\r\n\r\nCombine bivariate plot with marginal distributions.\r\n\r\n```python\r\ng = sns.JointGrid(data=df, x='total_bill', y='tip')\r\ng.plot_joint(sns.scatterplot)\r\ng.plot_marginals(sns.histplot)\r\n```",
"Core Plotting Interfaces": "(\r\n so.Plot(data=df, x='total_bill', y='tip')\r\n .add(so.Dot(), color='day')\r\n .add(so.Line(), so.PolyFit())\r\n)\r\n```",
"Best Practices": "sns.barplot(data=df, x='category', y='value',\r\n estimator='median', # Use median instead\r\n errorbar=('ci', 95)) # Bootstrapped CI\r\n```\r\n\r\n### 6. Combine with Matplotlib\r\n\r\nSeaborn integrates seamlessly with matplotlib for fine-tuning:\r\n\r\n```python\r\nax = sns.scatterplot(data=df, x='x', y='y')\r\nax.set(xlabel='Custom X Label', ylabel='Custom Y Label',\r\n title='Custom Title')\r\nax.axhline(y=0, color='r', linestyle='--')\r\nplt.tight_layout()\r\n```\r\n\r\n### 7. Save High-Quality Figures\r\n\r\n```python\r\nfig = sns.relplot(data=df, x='x', y='y', col='group')\r\nfig.savefig('figure.png', dpi=300, bbox_inches='tight')\r\nfig.savefig('figure.pdf') # Vector format for publications\r\n```",
"Plotting Functions by Category": "sns.clustermap(data, cmap='viridis',\r\n standard_scale=1, figsize=(10, 10))\r\n```",
"Resources": "This skill includes reference materials for deeper exploration:\r\n\r\n### references/\r\n\r\n- `function_reference.md` - Comprehensive listing of all seaborn functions with parameters and examples\r\n- `objects_interface.md` - Detailed guide to the modern seaborn.objects API\r\n- `examples.md` - Common use cases and code patterns for different analysis scenarios\r\n\r\nLoad reference files as needed for detailed function signatures, advanced parameters, or specific examples.",
"Data Structure Requirements": "control treatment\r\n0 10.5 12.3\r\n1 9.8 13.1\r\n```\r\n\r\n**Use cases:**\r\n- Simple time series\r\n- Correlation matrices\r\n- Heatmaps\r\n- Quick plots of array data\r\n\r\n**Converting wide to long:**\r\n```python\r\ndf_long = df.melt(var_name='condition', value_name='measurement')\r\n```",
"Design Philosophy": "Seaborn follows these core principles:\r\n\r\n1. **Dataset-oriented**: Work directly with DataFrames and named variables rather than abstract coordinates\r\n2. **Semantic mapping**: Automatically translate data values into visual properties (colors, sizes, styles)\r\n3. **Statistical awareness**: Built-in aggregation, error estimation, and confidence intervals\r\n4. **Aesthetic defaults**: Publication-ready themes and color palettes out of the box\r\n5. **Matplotlib integration**: Full compatibility with matplotlib customization when needed",
"Common Patterns": "g = sns.relplot(data=timeseries, x='date', y='measurement',\r\n col='location', hue='sensor', kind='line',\r\n height=4, aspect=1.5, errorbar=('ci', 95))\r\ng.set_axis_labels('Date', 'Measurement (units)')\r\n```",
"Troubleshooting": "sns.kdeplot(data=df, x='x', bw_adjust=0.5) # Less smooth\r\nsns.kdeplot(data=df, x='x', bw_adjust=2) # More smooth\r\n```",
"Figure-Level vs Axes-Level Functions": "sns.relplot(data=df, x='x', y='y', col='category', row='group',\r\n hue='type', height=3, aspect=1.2)\r\n```",
"Color Palettes": "palette = sns.diverging_palette(250, 10, as_cmap=True)\r\n```",
"Quick Start": "sns.scatterplot(data=df, x='total_bill', y='tip', hue='day')\r\nplt.show()\r\n```"
}
}---
name: seaborn
description: "Statistical visualization. Scatter, box, violin, heatmaps, pair plots, regression, correlation matrices, KDE, faceted plots, for exploratory analysis and publication figures."
---
# Seaborn Statistical Visualization
## Overview
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.
## Design Philosophy
Seaborn follows these core principles:
1. **Dataset-oriented**: Work directly with DataFrames and named variables rather than abstract coordinates
2. **Semantic mapping**: Automatically translate data values into visual properties (colors, sizes, styles)
3. **Statistical awareness**: Built-in aggregation, error estimation, and confidence intervals
4. **Aesthetic defaults**: Publication-ready themes and color palettes out of the box
5. **Matplotlib integration**: Full compatibility with matplotlib customization when needed
## Quick Start
```python
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()
```
## Core Plotting Interfaces
### Function Interface (Traditional)
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:**
- Quick exploratory analysis
- Single-purpose visualizations
- When you need a specific plot type
### Objects Interface (Modern)
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
```python
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())
)
```
## Plotting Functions by Category
### Relational Plots (Relationships Between Variables)
**Use for:** Exploring how two or more variables relate to each other
- `scatterplot()` - Display individual observations as points
- `lineplot()` - Show trends and changes (automatically aggregates and computes CI)
- `relplot()` - Figure-level interface with automatic faceting
**Key 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)
```python
# 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')
```
### Distribution Plots (Single and Bivariate Distributions)
**Use for:** Understanding data spread, shape, and probability density
- `histplot()` - Bar-based frequency distributions with flexible binning
- `kdeplot()` - Smooth density estimates using Gaussian kernels
- `ecdfplot()` - Empirical cumulative distribution (no parameters to tune)
- `rugplot()` - Individual observation tick marks
- `displot()` - Figure-level interface for univariate and bivariate distributions
- `jointplot()` - Bivariate plot with marginal distributions
- `pairplot()` - Matrix of pairwise relationships across dataset
**Key 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"
```python
# 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)
```
### Categorical Plots (Comparisons Across Categories)
**Use for:** Comparing distributions or statistics across discrete categories
**Categorical scatterplots:**
- `stripplot()` - Points with jitter to show all observations
- `swarmplot()` - Non-overlapping points (beeswarm algorithm)
**Distribution comparisons:**
- `boxplot()` - Quartiles and outliers
- `violinplot()` - KDE + quartile information
- `boxenplot()` - Enhanced boxplot for larger datasets
**Statistical estimates:**
- `barplot()` - Mean/aggregate with confidence intervals
- `pointplot()` - Point estimates with connecting lines
- `countplot()` - Count of observations per category
**Figure-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"
```python
# 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')
```
### Regression Plots (Linear Relationships)
**Use for:** Visualizing linear regressions and residuals
- `regplot()` - Axes-level regression plot with scatter + fit line
- `lmplot()` - Figure-level with faceting support
- `residplot()` - Residual plot for assessing model fit
**Key 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
```python
# 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')
```
### Matrix Plots (Rectangular Data)
**Use for:** Visualizing matrices, correlations, and grid-structured data
- `heatmap()` - Color-encoded matrix with annotations
- `clustermap()` - Hierarchically-clustered heatmap
**Key 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
```python
# 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))
```
## Multi-Plot Grids
Seaborn provides grid objects for creating complex multi-panel figures:
### FacetGrid
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.
```python
g = sns.FacetGrid(df, col='time', row='sex', hue='smoker')
g.map(sns.scatterplot, 'total_bill', 'tip')
g.add_legend()
```
### PairGrid
Show pairwise relationships between all variables in a dataset.
```python
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
Combine bivariate plot with marginal distributions.
```python
g = sns.JointGrid(data=df, x='total_bill', y='tip')
g.plot_joint(sns.scatterplot)
g.plot_marginals(sns.histplot)
```
## Figure-Level vs Axes-Level Functions
Understanding this distinction is crucial for effective seaborn usage:
### Axes-Level Functions
- Plot to a single matplotlib `Axes` object
- Integrate easily into complex matplotlib figures
- Accept `ax=` parameter for precise placement
- Return `Axes` object
- Examples: `scatterplot`, `histplot`, `boxplot`, `regplot`, `heatmap`
**When to use:**
- Building custom multi-plot layouts
- Combining different plot types
- Need matplotlib-level control
- Integrating with existing matplotlib code
```python
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])
```
### Figure-Level Functions
- Manage entire figure including all subplots
- Built-in faceting via `col` and `row` parameters
- Return `FacetGrid`, `JointGrid`, or `PairGrid` objects
- Use `height` and `aspect` for sizing (per subplot)
- Cannot be placed in existing figure
- Examples: `relplot`, `displot`, `catplot`, `lmplot`, `jointplot`, `pairplot`
**When to use:**
- Faceted visualizations (small multiples)
- Quick exploratory analysis
- Consistent multi-panel layouts
- Don't need to combine with other plot types
```python
# Automatic faceting
sns.relplot(data=df, x='x', y='y', col='category', row='group',
hue='type', height=3, aspect=1.2)
```
## Data Structure Requirements
### Long-Form Data (Preferred)
Each variable is a column, each observation is a row. This "tidy" format provides maximum flexibility:
```python
# 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:**
- Works with all seaborn functions
- Easy to remap variables to visual properties
- Supports arbitrary complexity
- Natural for DataFrame operations
### Wide-Form Data
Variables are spread across columns. Useful for simple rectangular data:
```python
# Wide-form structure
control treatment
0 10.5 12.3
1 9.8 13.1
```
**Use cases:**
- Simple time series
- Correlation matrices
- Heatmaps
- Quick plots of array data
**Converting wide to long:**
```python
df_long = df.melt(var_name='condition', value_name='measurement')
```
## Color Palettes
Seaborn provides carefully designed color palettes for different data types:
### Qualitative Palettes (Categorical Data)
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
```python
sns.set_palette("colorblind")
sns.color_palette("Set2")
```
### Sequential Palettes (Ordered Data)
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
```python
sns.heatmap(data, cmap='rocket')
sns.kdeplot(data=df, x='x', y='y', cmap='mako', fill=True)
```
### Diverging Palettes (Centered Data)
Emphasize deviations from a midpoint:
- `"vlag"` - Blue to red
- `"icefire"` - Blue to orange
- `"coolwarm"` - Cool to warm
- `"Spectral"` - Rainbow diverging
```python
sns.heatmap(correlation_matrix, cmap='vlag', center=0)
```
### Custom Palettes
```python
# 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)
```
## Theming and Aesthetics
### Set Theme
`set_theme()` controls overall appearance:
```python
# Set complete theme
sns.set_theme(style='whitegrid', palette='pastel', font='sans-serif')
# Reset to defaults
sns.set_theme()
```
### Styles
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
```python
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')
```
### Contexts
Scale elements for different use cases:
- `"paper"` - Smallest (default)
- `"notebook"` - Slightly larger
- `"talk"` - Presentation slides
- `"poster"` - Large format
```python
sns.set_context("talk", font_scale=1.2)
# Temporary context
with sns.plotting_context("poster"):
sns.barplot(data=df, x='category', y='value')
```
## Best Practices
### 1. Data Preparation
Always use well-structured DataFrames with meaningful column names:
```python
# 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. Choose the Right Plot Type
**Continuous x, continuous y:** `scatterplot`, `lineplot`, `kdeplot`, `regplot`
**Continuous x, categorical y:** `violinplot`, `boxplot`, `stripplot`, `swarmplot`
**One continuous variable:** `histplot`, `kdeplot`, `ecdfplot`
**Correlations/matrices:** `heatmap`, `clustermap`
**Pairwise relationships:** `pairplot`, `jointplot`
### 3. Use Figure-Level Functions for Faceting
```python
# 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. Leverage Semantic Mappings
Use `hue`, `size`, and `style` to encode additional dimensions:
```python
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. Control Statistical Estimation
Many functions compute statistics automatically. Understand and customize:
```python
# 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. Combine with Matplotlib
Seaborn integrates seamlessly with matplotlib for fine-tuning:
```python
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. Save High-Quality Figures
```python
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
```
## Common Patterns
### Exploratory Data Analysis
```python
# 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)
```
### Publication-Quality Figures
```python
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')
```
### Complex Multi-Panel Figures
```python
# 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()
```
### Time Series with Confidence Bands
```python
# 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)')
```
## Troubleshooting
### Issue: Legend Outside Plot Area
Figure-level functions place legends outside by default. To move inside:
```python
g = sns.relplot(data=df, x='x', y='y', hue='category')
g._legend.set_bbox_to_anchor((0.9, 0.5)) # Adjust position
```
### Issue: Overlapping Labels
```python
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
```
### Issue: Figure Too Small
For figure-level functions:
```python
sns.relplot(data=df, x='x', y='y', height=6, aspect=1.5)
```
For axes-level functions:
```python
fig, ax = plt.subplots(figsize=(10, 6))
sns.scatterplot(data=df, x='x', y='y', ax=ax)
```
### Issue: Colors Not Distinct Enough
```python
# 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)
```
### Issue: KDE Too Smooth or Jagged
```python
# 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
```
## Resources
This skill includes reference materials for deeper exploration:
### references/
- `function_reference.md` - Comprehensive listing of all seaborn functions with parameters and examples
- `objects_interface.md` - Detailed guide to the modern seaborn.objects API
- `examples.md` - Common use cases and code patterns for different analysis scenarios
Load reference files as needed for detailed function signatures, advanced parameters, or specific examples.