Seaborn is a statistical data visualization library built on top of Matplotlib. Its primary strength lies in its native integration with Pandas DataFrames, automatically calculating aggregates, confidence intervals, and kernel density estimates (KDE) while mapping high-dimensional variables to intuitive semantic channels (x, y, hue, style, size, col, row).
🔗 Related Cheat Sheets: Pandas Cheat Sheet · NumPy Cheat Sheet · Bokeh Cheat Sheet · Data Analysis Methods · Scikit-Learn Cheat Sheet · Python Cheat Sheet
1. Core Architecture: Figure-level vs. Axes-level Functions
Modern Seaborn organizes visualization around a clear two-tier hierarchy:
| Analytical Task | Figure-level Facet Interface (returns FacetGrid) |
Underlying Axes-level Functions (plot on specific ax) |
Primary Target |
|---|---|---|---|
| Relational | sns.relplot(...) |
sns.scatterplot()sns.lineplot() |
Bivariate relationships, temporal trends, multi-feature scatter |
| Distribution | sns.displot(...) |
sns.histplot()sns.kdeplot()sns.ecdfplot()sns.rugplot() |
Univariate and bivariate density, frequency histograms, cumulative distributions |
| Categorical | sns.catplot(...) |
sns.stripplot() / sns.swarmplot()sns.boxplot() / sns.violinplot()sns.barplot() / sns.pointplot()sns.countplot() |
Categorical comparisons, group-wise distributions, point estimates & intervals |
2. End-to-End Quickstart Example
import matplotlib.pyplot as plt
import seaborn as sns
# 1. Configure modern academic theme
sns.set_theme(style="whitegrid", palette="deep")
# 2. Load built-in DataFrame
tips = sns.load_dataset("tips")
# 3. Figure-level multi-facet categorical plot
g = sns.catplot(
data=tips,
x="day", y="total_bill", hue="sex",
col="time", # Split by Lunch / Dinner into two subplots
kind="violin",
split=True, # Merge male/female into single split violins
inner="quart", # Draw quartile lines
aspect=1.2, height=4.5
)
# 4. Polish labels and titles
g.set_axis_labels("Day of Week", "Total Bill ($)")
g.set_titles(col_template="Time: {col_name}")
# 5. Save and display
g.savefig("tips_violin.png", dpi=300, bbox_inches="tight")
plt.show()
3. Themes, Styles & Palettes
3.1 Global Theme Setup
# 1. Standard theme configuration
sns.set_theme(
context="notebook", # Scaling preset: "paper", "notebook", "talk", "poster"
style="whitegrid", # Background style: "whitegrid", "darkgrid", "white", "dark", "ticks"
palette="deep", # Global palette
font="sans-serif",
rc={"lines.linewidth": 2.0}
)
# 2. Despine top and right axis spines
sns.despine(top=True, right=True, left=False, bottom=False)
3.2 Color Palettes
# Qualitative (distinct categories without ordering)
sns.color_palette("deep") # "deep", "muted", "pastel", "bright", "dark", "colorblind"
sns.color_palette("tab10")
# Sequential (numeric intensity from low to high)
sns.color_palette("rocket", as_cmap=True) # "mako", "flare", "crest", "viridis"
# Diverging (deviations around a neutral center point)
sns.color_palette("vlag", as_cmap=True) # "coolwarm", "icefire"
# Apply temporarily via context manager
with sns.color_palette("husl", 8):
sns.lineplot(data=df)
4. Relational Plots (relplot)
# Figure-level relational scatter plot with facetting
g = sns.relplot(
data=tips,
x="total_bill", y="tip",
hue="smoker", # Color mapping
style="time", # Marker shape mapping
size="size", # Marker area sizing
col="sex", # Subplot columns
kind="scatter",
alpha=0.8
)
Axes-level Functions (scatterplot & lineplot)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
# 1. Scatterplot
sns.scatterplot(
data=tips, x="total_bill", y="tip", hue="day", size="size",
palette="viridis", ax=ax1
)
# 2. Lineplot (automatically computes mean and 95% confidence interval band)
fmri = sns.load_dataset("fmri")
sns.lineplot(
data=fmri, x="timepoint", y="signal",
hue="event", style="region",
errorbar="ci", # Error band: "ci" (confidence interval), "sd", "se", None
ax=ax2
)
5. Distribution Plots (displot)
⚠️ Note:
sns.distplothas been completely removed. Usedisplot,histplot, orkdeplot.
# Figure-level stacked histogram with KDE overlay
sns.displot(
data=tips, x="total_bill", hue="sex",
kind="hist", # "hist", "kde", "ecdf"
kde=True,
multiple="stack", # "layer", "dodge", "stack", "fill"
bins=30,
col="time"
)
Axes-level Distribution Functions
# 1. Histplot
sns.histplot(data=tips, x="total_bill", bins=20, kde=True, stat="density")
# 2. Bivariate KDE density contours
sns.kdeplot(data=tips, x="total_bill", y="tip", hue="sex", fill=True, levels=5)
# 3. Empirical Cumulative Distribution (ECDF)
sns.ecdfplot(data=tips, x="total_bill", hue="smoker")
# 4. Rug plot (marginal tick indicators)
sns.rugplot(data=tips, x="total_bill", height=0.05, color="black")
6. Categorical Plots (catplot)
⚠️ Note:
sns.factorplotwas deprecated and completely removed. Usesns.catplot.
| Function | Plot Type | Visual Mechanism & Use Case |
|---|---|---|
sns.stripplot() |
Jittered Scatter | Shows all raw sample points along category axes with random jitter |
sns.swarmplot() |
Bee Swarm | Algorithmic non-overlapping points; optimal for small-sample distributions |
sns.boxplot() |
Box & Whisker | Displays five-number summaries (min, Q1, median, Q3, max) and outliers |
sns.boxenplot() |
Enhanced Boxen | Multi-quantile boxes tailored for large, heavy-tailed tabular distributions |
sns.violinplot() |
Violin Plot | Combines boxplots with mirrored kernel density estimation |
sns.barplot() |
Bar Estimate | Bar height indicates mean estimator; vertical error bars show 95% CI |
sns.pointplot() |
Point & Line | Plots mean point estimates connected by lines to highlight interaction effects |
sns.countplot() |
Frequency Count | Bar chart showing discrete observation counts per category |
# Overlay boxplot with swarmplot for complete distribution transparency
fig, ax = plt.subplots(figsize=(8, 5))
sns.boxplot(data=tips, x="day", y="total_bill", color="white", ax=ax)
sns.swarmplot(data=tips, x="day", y="total_bill", hue="sex", dodge=True, size=4, ax=ax)
7. Regression & Residual Plots
# 1. High-order polynomial regression across facets
sns.lmplot(
data=tips,
x="total_bill", y="tip", hue="smoker",
col="time", row="sex",
order=2, # 2nd-order polynomial fit
scatter_kws={"alpha": 0.5},
line_kws={"linewidth": 2}
)
# 2. Single-axis robust regression (Huber estimator, suppresses outliers)
sns.regplot(data=tips, x="total_bill", y="tip", robust=True, ci=95)
# 3. Residual diagnostics plot
sns.residplot(data=tips, x="total_bill", y="tip", lowess=True)
8. Heatmaps & Clustermaps
# 1. Correlation matrix heatmap
corr = tips.select_dtypes(include="number").corr()
fig, ax = plt.subplots(figsize=(6, 5))
sns.heatmap(
corr,
annot=True, # Annotate cell values
fmt=".2f", # Floating-point format
cmap="coolwarm", # Diverging colormap
vmin=-1.0, vmax=1.0,
square=True,
linewidths=0.5,
ax=ax
)
# 2. Hierarchically-clustered heatmap
iris = sns.load_dataset("iris")
species = iris.pop("species")
sns.clustermap(
iris,
method="average", # Clustering linkage: "ward", "complete", "average"
metric="euclidean",
standard_scale=1, # Normalize across columns
cmap="mako"
)
9. Multi-Plot Pairwise & Joint Grids
9.1 Pairplot (pairplot)
Essential for Exploratory Data Analysis (EDA):
iris = sns.load_dataset("iris")
sns.pairplot(
iris,
hue="species",
diag_kind="kde", # Diagonal KDE density plots
corner=True, # Plots only lower triangle to eliminate duplicate comparisons
palette="Set2"
)
9.2 Jointplot (jointplot)
# Center bivariate scatter with top and right marginal histograms/KDEs
sns.jointplot(
data=tips,
x="total_bill", y="tip",
hue="sex",
kind="scatter", # "scatter", "kde", "hist", "hex", "reg", "resid"
marginal_ticks=True
)
10. Saving & Exporting
# Polish Matplotlib Axis
ax = sns.scatterplot(data=tips, x="total_bill", y="tip")
ax.set_title("Total Bill vs Tip Correlation", fontsize=14, weight="bold")
ax.set_xlim(0, 60)
ax.set_ylim(0, 12)
# Export publication-ready images
plt.tight_layout()
plt.savefig("plot.png", dpi=300, bbox_inches="tight")
plt.savefig("plot.svg", format="svg") # Vector publication format
plt.close()