Seaborn Guide & Cookbook (Python)

Seaborn Cookbook & Tutorial Hub

A practical, copy‑ready guide to Seaborn with examples you actually use at work. Organized by chart family, with code snippets and pitfalls.

Why Seaborn? Seaborn sits on top of Matplotlib and gives you high‑level, beautiful defaults for statistical plots. Instead of wiring styles and legends by hand, you can get publication‑ready plots with a few lines—then drop down to Matplotlib when you need pixel‑level control.

What this hub covers: 35+ recipes organized by chart families—distributions, relationships, categorical comparisons, heatmaps and clusters, facets/grids, figure‑ vs axes‑level APIs, annotations, and themes. Each section starts with a short explanation, a code example, and a connector that previews what the tutorials cover.

How to use it: Skim the examples, then dive into the specific tutorial that matches your task. All code has been tested on Seaborn 0.12–0.13 and Matplotlib 3.7+.

Seaborn Histogram, KDE & ECDF Tutorial

Distribution plots help you understand the shape, spread, and skew of a variable and how it differs across groups. Seaborn’s histplot, kdeplot, and ecdfplot provide sensible defaults and quick grouping via hue.

import seaborn as sns, matplotlib.pyplot as plt
penguins = sns.load_dataset("penguins")
sns.histplot(data=penguins, 
             x="bill_length_mm", 
             hue="species", 
             element="step", 
             stat="density", 
             common_norm=False)
plt.title("Distribution of Bill Length by Species");
 plt.tight_layout()

The snippet above shows a simple histogram. But Seaborn makes it easy to go further: create Seaborn histograms with custom bins, combine KDE plots, or add ECDF lines for distribution comparison. The tutorials below cover displot, histplot, KDE, and ECDF in depth

Seaborn Scatterplot & Regression Plot Examples

Relationship plots reveal associations across numerical variables (scatter/line) with optional trend estimation via regplot and lmplot. Use hue, size, and style to encode additional dimensions.

sns.set_theme(style="whitegrid")
tips = sns.load_dataset("tips")
sns.lmplot(data=tips, 
           x="total_bill", 
           y="tip",
           hue="smoker", 
           height=4, 
           aspect=1.3, 
           scatter_kws={{"alpha":0.6}})
plt.title("Bill vs Tip with Regression by Smoker"); 
plt.tight_layout()

From scatterplots to regression lines, Seaborn provides flexible options with regplot, lmplot, and lineplot. Learn how to add confidence intervals, facet by category, and use relplot for multi-variable relationships. These guides show practical Seaborn scatterplot tutorials and regression use cases.

Seaborn Boxplot, Violin & Barplot Tutorials

Categorical plots compare distributions or averages across discrete groups. Use boxplot/violinplot for distribution shape and outliers, barplot/countplot for aggregated values or counts.

sns.set_theme(style="whitegrid")
sns.boxplot(data=tips, 
            x="day", 
            y="total_bill", 
            hue="smoker", 
            showfliers=False)
sns.stripplot(data=tips, 
              x="day",
              y="total_bill",
              hue="smoker", 
              dodge=True, 
              alpha=0.4, 
              linewidth=0)
plt.title("Bill Distribution by Day (with jitter)"); 
plt.tight_layout()

Categorical plots let you compare distributions and summaries across groups. Seaborn’s boxplot and violinplot highlight spread and outliers, while barplot and countplot show means or counts with confidence intervals. The tutorials below expand beyond basics to grouped bars, split violins, and swarm overlays.

Seaborn Heatmap & Clustermap Guide

Matrix plots summarize pairwise relationships or magnitudes. heatmap is ideal for correlations and pivoted tables; clustermap adds hierarchical clustering to reveal structure.

import numpy as np
iris = sns.load_dataset("iris")
corr = iris.drop(columns=["species"]).corr()
sns.heatmap(corr, 
            annot=True,
            cmap="vlag", 
            center=0)
plt.title("Iris Feature Correlations"); 
plt.tight_layout()

Seaborn heatmaps are perfect for correlations and pivot tables, while clustermap reveals hidden structure through hierarchical clustering. The tutorials below cover annotated Seaborn heatmaps, triangular masks for correlations, and clustermap customization.

Seaborn FacetGrid, PairGrid & Pairplot

Facets create small multiples for subgroups, aiding comparison without overplotting. FacetGrid maps a plotting function across subsets, while pairplot shows pairwise relationships quickly.

sns.pairplot(penguins, 
            hue="species",
            corner=True, 
            diag_kind="kde")
plt.suptitle("Pairwise Relationships in Penguins", y=1.02); 
plt.tight_layout()

For multi-facet layouts, Seaborn offers FacetGrid and relplot, while PairGrid and pairplot visualize all variable combinations. These tutorials cover facetting by category, customizing legends, and producing publication-ready Seaborn pairplot guides.

Seaborn Legends, Labels & Annotations

Annotation and labeling polish helps readers interpret the plot quickly. Control legends and titles from Seaborn, then finish with Matplotlib for precise typographic control.

ax = sns.scatterplot(data=tips,
                     x="total_bill",
                     y="tip",
                     hue="time",
                     alpha=0.7)
ax.legend(title="Meal"); 
ax.set(xlabel="Bill ($)", 
       ylabel="Tip ($)",
       title="Tipping Patterns")
sns.move_legend(ax,
               "upper left", 
                bbox_to_anchor=(1,1));
 plt.tight_layout()

A well-designed figure needs clean labels and legends. Seaborn handles defaults, but you can refine with Matplotlib for titles, axis labels, and custom annotation. The tutorials below show how to add legends, move them outside the plot, and annotate points clearly.

Seaborn Themes, Color Palettes & Style Examples

Seaborn’s theme system sets sensible defaults. Combine with Matplotlib rcParams for publication‑quality output. Prefer perceptually uniform colormaps for quantitative data (see ColorBrewer for accessible palette choices).

sns.set_theme(context="talk", 
              style="whitegrid",
              palette="deep")
# Optional: fine-tune Matplotlib
import matplotlib as mpl
mpl.rcParams["axes.titlesize"] = 12
mpl.rcParams["axes.labelsize"] = 10

With a single call to set_theme, Seaborn applies consistent style across all plots. Customize with palettes (deep, colorblind, viridis) and contexts (talk, paper) for presentations or publications. The tutorials below cover Seaborn color palettes, style settings, and Matplotlib rcParams integration.

Seaborn Tips, Performance & Export Recipes

Additional tips that don’t fit neatly in the above families: performance, exporting figures (PNG/SVG/PDF), and integrating with pandas plotting or seaborn‑objects.

Performance, exporting (PNG/SVG/PDF), and integration patterns you’ll reuse—start with these quick wins.

Seaborn FAQs

When should I use figure-level vs axes-level functions?

Use figure-level (e.g., displot, relplot, catplot) when you want automatic multi-facet layouts and consistent legends. Use axes-level (e.g., histplot, scatterplot) when you need fine Matplotlib control on a specific Axes (dashboards, tight layouts).

How do I make figures look consistent across notebooks and slides?

Call sns.set_theme(context="talk", style="whitegrid", palette="deep") once at the top. For reproducibility, pin Matplotlib rcParams (e.g., fonts) and print versions: import seaborn, matplotlib; print(seaborn.__version__, matplotlib.__version__).

My scatter plot is overplotted. How can I fix it?

Use alpha and size, or binning. Example:
sns.scatterplot(..., alpha=0.4, s=20), or switch to sns.histplot/hexbin via Matplotlib:
plt.hexbin(x, y, gridsize=40, cmap="mako"). For large data, pre-aggregate in pandas or sample.

How do I choose color-blind-friendly palettes?

Use Seaborn palettes like colorblind or Matplotlib’s perceptually uniform colormaps (e.g., viridis, mako, rocket) for quantitative values. Avoid rainbow for ordered data.

How can I control binning and normalization in histograms/KDE?

Use bins=, binwidth=, and stat= (e.g., stat="density"). KDE bandwidth can be tuned with bw_adjust. Example:
sns.histplot(df, x="value", bins=40, stat="density"); sns.kdeplot(df["value"], bw_adjust=1.2).

How do I manage legends in FacetGrid or multi-axes figures?

For figure-level: g = sns.relplot(...); g.add_legend(). For axes-level grids, create a single legend from handles and place it outside:
ax.legend(bbox_to_anchor=(1,1), loc="upper left"). Remove duplicates on subplots to avoid clutter.

How can I annotate points/lines clearly?

Use Matplotlib’s annotate with offsets and arrows. Example:
ax.annotate("Outlier", (x,y), xytext=(10,10), textcoords="offset points", arrowprops=dict(arrowstyle="->")). Keep annotations minimal and readable.

Heatmap best practices: scaling, masks, and labels?

Center diverging data at 0 with center=0, apply annot=True for labels, and use masks for triangular correlation plots:
mask = np.triu(np.ones_like(corr, dtype=bool)); sns.heatmap(corr, mask=mask, cmap="vlag", center=0).

How do I export crisp figures for blogs and papers?

Use vector formats for line art (SVG/PDF), high-DPI PNG for raster. Example:
plt.savefig("fig.png", dpi=200, bbox_inches="tight"). Ensure fonts are embedded and color choices are accessible.

Seaborn vs Matplotlib vs Plotly — what should I use?

Seaborn: fast statistical plots with good defaults. Matplotlib: ultimate control for custom layouts. Plotly: interactivity and web sharing. Many workflows start in Seaborn and finish with Matplotlib polish.

Performance tips for large datasets?

Downsample or aggregate first (pandas groupby or binning). Use smaller markers, alpha<1, and consider rasterization for heavy scatters. For huge data, datashader/holoviews → then style in Seaborn/Matplotlib.

I see warnings after upgrading Seaborn/Matplotlib. What do I do?

Pin compatible versions (e.g., Seaborn 0.12–0.13 with Matplotlib 3.7+), review release notes, and remove deprecated args. Set your theme in code for consistent styling across environments.

Want to use ggplot2 in R?

We also maintain a complete ggplot2 guide with 35+ tutorials and recipes.

Explore the ggplot2 Guide →


  • Activation Functions in Neural Networks – Visual Guide
  • Exit mobile version