seaborn
seaborn draws statistical plots from a tidy table, with one row per observation and one
column per variable. You name the columns for x, y, and hue, and seaborn does the
grouping, the colors, and the legend. Every function returns Matplotlib objects, so the
Matplotlib cheatsheet covers the finishing touches.
seaborn 0.12 also added seaborn.objects, an interface close to ggplot2; this page sticks to
the function interface that most code uses.
Quick reference
Section titled “Quick reference”| Task | Code |
|---|---|
| Theme | sns.set_theme(style="ticks", context="paper") |
| Box plot | sns.boxplot(data=df, x="group", y="value", hue="group") |
| Violin | sns.violinplot(data=df, x="group", y="value", cut=0) |
| Points over a box | sns.stripplot(data=df, x="group", y="value", color="black") |
| Swarm | sns.swarmplot(data=df, x="group", y="value", hue="batch") |
| Dodge by a second column | sns.boxplot(data=df, x="group", y="value", hue="batch") |
| Histogram per group | sns.histplot(data=df, x="value", hue="batch", stat="density", common_norm=False) |
| Density | sns.kdeplot(data=df, x="value", hue="batch") |
| Mean and error bar | sns.barplot(data=df, x="group", y="value", errorbar="sd") |
| Count per category | sns.countplot(data=df, x="group", hue="band") |
| Time course with CI | sns.lineplot(data=df, x="hours", y="value", hue="group", seed=42) |
| Regression line | sns.regplot(data=df, x="x", y="y") |
| Scatter with mappings | sns.scatterplot(data=df, x="PC1", y="PC2", hue="group", size="viability") |
| Legend outside | sns.move_legend(ax, "upper left", bbox_to_anchor=(1, 1)) |
| Heatmap | sns.heatmap(m, cmap="RdBu_r", center=0, annot=True) |
| Clustered heatmap | sns.clustermap(m, z_score=0, col_colors=colors) |
| Panels | sns.catplot(..., col="gene", col_wrap=3, kind="box") |
| Pairs | sns.pairplot(df, hue="group", corner=True) |
| Palette | sns.color_palette("colorblind", 3).as_hex() |
| Axis labels | ax.set(xlabel="", ylabel="log2 CPM") |
| Save a grid | g.savefig("fig.png", dpi=300, bbox_inches="tight") |
Example data
Section titled “Example data”One simulated experiment runs through the page, with 200 genes in 24 samples, 8 per group,
split across two batches. Drug A shifts GENE001 to GENE004 by 1.5 to 2.5 log2 units. Drug B
shifts the same four by about half as much and also moves GENE005 and GENE006. Batch b2
reads 0.5 log2 units higher on every gene.
from pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport seaborn as snsfrom matplotlib.patches import Patch
Path("outputs").mkdir(exist_ok=True)pd.set_option("display.width", 80)rng = np.random.default_rng(42)sns.set_theme(style="ticks")
groups = ["control", "drug_a", "drug_b"]samples = pd.DataFrame({ "sample": [f"S{i:02d}" for i in range(1, 25)], "group": np.repeat(groups, 8), "batch": np.tile(["b1", "b2"], 12),})
n_genes = 200genes = [f"GENE{i:03d}" for i in range(1, n_genes + 1)]# Shift against control in log2 units: columns are control, drug_a, drug_b.effect = np.zeros((n_genes, 3))effect[:4, 1] = [2.5, 1.8, -2.0, -1.5]effect[:4, 2] = [1.2, 0.9, -1.0, -0.6]effect[4:6, 2] = [1.5, -1.5]group_index = np.repeat([0, 1, 2], 8)batch_shift = np.where(samples["batch"] == "b2", 0.5, 0.0)log_cpm = (rng.normal(7, 1.5, (n_genes, 1)) + effect[:, group_index] + batch_shift + rng.normal(0, 0.5, (n_genes, 24)))expr = pd.DataFrame(log_cpm, index=genes, columns=samples["sample"])
# Viability falls as GENE001 rises.gene1 = expr.loc["GENE001"].to_numpy()samples["viability"] = (90 - 6 * (gene1 - gene1[:8].mean()) + rng.normal(0, 3, 24)).round(1)palette = dict(zip(groups, sns.color_palette("colorblind", 3).as_hex()))Most seaborn functions want the long form. melt turns the gene by sample matrix into one
row per gene and sample, and merge adds the sample sheet.
long = ( expr.rename_axis("gene").reset_index() .melt(id_vars="gene", var_name="sample", value_name="log2_cpm") .merge(samples, on="sample"))gene1_long = long[long["gene"] == "GENE001"]print(long.shape)print(long.head().round(2))(4800, 6) gene sample log2_cpm group batch viability0 GENE001 S01 7.63 control b1 89.11 GENE002 S01 5.49 control b1 89.12 GENE003 S01 9.58 control b1 89.13 GENE004 S01 8.36 control b1 89.14 GENE005 S01 4.22 control b1 89.1Box plot
Section titled “Box plot”seaborn 0.13 deprecated palette without hue. Set hue to the same column as x, and
seaborn drops the legend that would repeat the axis labels.
fig, ax = plt.subplots(figsize=(4.5, 4), layout="constrained")sns.boxplot(data=gene1_long, x="group", y="log2_cpm", hue="group", palette=palette, ax=ax)ax.set(xlabel="", ylabel="GENE001 log2 CPM")fig.savefig("outputs/seaborn-boxplot.png", dpi=150, bbox_inches="tight")plt.close(fig)
Violin plot
Section titled “Violin plot”The violin adds the shape of the distribution. cut=0 stops the density at the observed
range. density_norm="width" gives every violin the same width; it replaced
scale="width" in seaborn 0.13.
fig, ax = plt.subplots(figsize=(4.5, 4), layout="constrained")sns.violinplot(data=gene1_long, x="group", y="log2_cpm", hue="group", palette=palette, inner="quart", cut=0, density_norm="width", ax=ax)ax.set(xlabel="", ylabel="GENE001 log2 CPM")fig.savefig("outputs/seaborn-violin.png", dpi=150, bbox_inches="tight")plt.close(fig)
Box plot with points
Section titled “Box plot with points”Eight samples per group is few enough to show every point. showfliers=False hides the box
plot’s own outlier markers, so no sample appears twice. The strip plot jitter draws from
NumPy’s global random state, so seed it to get the same figure on every run.
np.random.seed(42) # stripplot jitter has no seed argumentfig, ax = plt.subplots(figsize=(4.5, 4), layout="constrained")sns.boxplot(data=gene1_long, x="group", y="log2_cpm", hue="group", palette=palette, showfliers=False, ax=ax)sns.stripplot(data=gene1_long, x="group", y="log2_cpm", color="black", size=4, jitter=0.15, ax=ax)ax.set(xlabel="", ylabel="GENE001 log2 CPM")fig.savefig("outputs/seaborn-box-strip.png", dpi=150, bbox_inches="tight")plt.close(fig)
Swarm plot
Section titled “Swarm plot”A swarm plot moves points sideways so none overlap. Coloring by a second column, here the batch, shows whether it explains the spread inside a group.
fig, ax = plt.subplots(figsize=(4.5, 4), layout="constrained")sns.swarmplot(data=gene1_long, x="group", y="log2_cpm", hue="batch", size=6, ax=ax)ax.set(xlabel="", ylabel="GENE001 log2 CPM")fig.savefig("outputs/seaborn-swarm.png", dpi=150, bbox_inches="tight")plt.close(fig)
Two grouping columns
Section titled “Two grouping columns”With hue set to a different column than x, seaborn dodges the boxes side by side. This is
the quick visual check for a batch effect inside each group.
fig, ax = plt.subplots(figsize=(5.5, 4), layout="constrained")sns.boxplot(data=gene1_long, x="group", y="log2_cpm", hue="batch", ax=ax)ax.set(xlabel="", ylabel="GENE001 log2 CPM")ax.legend(title="batch", frameon=False)fig.savefig("outputs/seaborn-hue-dodge.png", dpi=150, bbox_inches="tight")plt.close(fig)
Histogram and density
Section titled “Histogram and density”histplot with hue overlays one histogram per level. stat="density" with
common_norm=False scales each to an area of 1, so batches of different size compare fairly,
and element="step" keeps the overlap readable.
fig, ax = plt.subplots(figsize=(5.5, 4), layout="constrained")sns.histplot(data=long, x="log2_cpm", hue="batch", stat="density", common_norm=False, element="step", kde=True, ax=ax)ax.set_xlabel("log2 CPM, all genes and samples")fig.savefig("outputs/seaborn-histplot.png", dpi=150, bbox_inches="tight")plt.close(fig)
sns.kdeplot draws the curve alone, and sns.ecdfplot draws the cumulative distribution.
Bar plot with error bars
Section titled “Bar plot with error bars”barplot draws the mean and an error bar. seaborn 0.12 replaced the old ci= argument with
errorbar=, which takes "sd", "se", ("ci", 95), or ("pi", 50).
fig, ax = plt.subplots(figsize=(4.5, 4), layout="constrained")sns.barplot(data=samples, x="group", y="viability", hue="group", palette=palette, errorbar="sd", capsize=0.2, ax=ax)ax.set(xlabel="", ylabel="viability (%)")fig.savefig("outputs/seaborn-barplot.png", dpi=150, bbox_inches="tight")plt.close(fig)
Count plot
Section titled “Count plot”countplot counts rows per category, so it takes x and no y. Here pd.cut puts each
sample’s viability in one of three bands, and the plot counts the samples per group and band.
bands = samples.assign(viability_band=pd.cut( samples["viability"], bins=[0, 75, 85, 100], labels=["75 or less", "75 to 85", "above 85"],))print(pd.crosstab(bands["group"], bands["viability_band"]))
fig, ax = plt.subplots(figsize=(5.5, 4), layout="constrained")sns.countplot(data=bands, x="group", hue="viability_band", palette="crest", ax=ax)ax.set(xlabel="", ylabel="samples")ax.legend(title="viability (%)", frameon=False)fig.savefig("outputs/seaborn-countplot.png", dpi=150, bbox_inches="tight")plt.close(fig)viability_band 75 or less 75 to 85 above 85groupcontrol 0 2 6drug_a 4 4 0drug_b 0 7 1
Time course
Section titled “Time course”lineplot draws the mean at each x and a band around it. With several replicates per time
point the band is a bootstrap 95% confidence interval, so pass seed to get the same band
on every run. The example follows GENE001 for 24 hours in each group, four replicates per
time point.
hours = [0, 2, 4, 8, 12, 24]tc = pd.DataFrame( [(grp, h, rep) for grp in groups for h in hours for rep in range(1, 5)], columns=["group", "hours", "replicate"],)plateau = tc["group"].map({"control": 0.0, "drug_a": 2.5, "drug_b": 1.2})tc["log2_cpm"] = (7.5 + plateau * (1 - np.exp(-tc["hours"] / 4)) + rng.normal(0, 0.4, len(tc)))
fig, ax = plt.subplots(figsize=(5.5, 4), layout="constrained")sns.lineplot(data=tc, x="hours", y="log2_cpm", hue="group", palette=palette, marker="o", errorbar=("ci", 95), seed=42, ax=ax)ax.set(xlabel="hours after treatment", ylabel="GENE001 log2 CPM")fig.savefig("outputs/seaborn-lineplot.png", dpi=150, bbox_inches="tight")plt.close(fig)
errorbar="sd" draws one standard deviation instead, and units="replicate" with
estimator=None draws one line per replicate.
Regression plot
Section titled “Regression plot”regplot needs one row per sample, so pivot the genes back into columns and join the sample
sheet. The shaded band is a bootstrap 95% confidence interval for the fitted line, and
seed fixes the bootstrap so the band is the same on every run.
wide = expr.T.join(samples.set_index("sample"))print(wide[["GENE001", "viability"]].corr().round(2))
fig, ax = plt.subplots(figsize=(5, 4), layout="constrained")sns.regplot(data=wide, x="GENE001", y="viability", seed=42, ax=ax, scatter_kws={"s": 25})ax.set(xlabel="GENE001 log2 CPM", ylabel="viability (%)")fig.savefig("outputs/seaborn-regplot.png", dpi=150, bbox_inches="tight")plt.close(fig) GENE001 viabilityGENE001 1.00 -0.93viability -0.93 1.00
sns.lmplot(data=wide, x="GENE001", y="viability", hue="group") fits one line per group.
Scatter with hue and size
Section titled “Scatter with hue and size”scatterplot maps columns to color with hue, to marker size with size, and to marker
shape with style. PCA scores are a common case. The scores here come from an SVD of the
gene-centered matrix, and sns.move_legend puts the long legend outside the axes.
centered = expr.sub(expr.mean(axis=1), axis=0).to_numpy()_, s, vt = np.linalg.svd(centered, full_matrices=False)pct = 100 * s**2 / (s**2).sum()scores = samples.assign(PC1=vt[0] * s[0], PC2=vt[1] * s[1])
fig, ax = plt.subplots(figsize=(6, 4.2), layout="constrained")sns.scatterplot(data=scores, x="PC1", y="PC2", hue="group", size="viability", style="batch", sizes=(20, 200), palette=palette, ax=ax)ax.set(xlabel=f"PC1, {pct[0]:.0f}% of variance", ylabel=f"PC2, {pct[1]:.0f}% of variance")sns.move_legend(ax, "upper left", bbox_to_anchor=(1.01, 1), frameon=False)fig.savefig("outputs/seaborn-scatterplot.png", dpi=150, bbox_inches="tight")plt.close(fig)PC1 splits the two batches rather than the drugs. The batch shift touches all 200 genes and the drugs move six, so batch takes the first component and the groups separate on PC2.

Heatmap
Section titled “Heatmap”annot=True prints each value in its cell, which suits a small summary matrix. center=0
puts white at zero on a diverging colormap.
de_genes = genes[:6]means = (long[long["gene"].isin(de_genes)] .pivot_table(index="gene", columns="group", values="log2_cpm"))change = means.sub(means["control"], axis=0).drop(columns="control")
fig, ax = plt.subplots(figsize=(4, 4), layout="constrained")sns.heatmap(change, cmap="RdBu_r", center=0, annot=True, fmt=".1f", linewidths=0.5, cbar_kws={"label": "log2 change vs control"}, ax=ax)fig.savefig("outputs/seaborn-heatmap.png", dpi=150, bbox_inches="tight")plt.close(fig)
Clustermap
Section titled “Clustermap”clustermap clusters rows and columns and draws the dendrograms. z_score=0 scales each
row, and col_colors adds an annotation bar above the columns. It builds its own figure, so
it takes figsize directly and returns a grid object rather than an Axes.
top_var = expr.var(axis=1).nlargest(10).indexcol_colors = samples.set_index("sample")["group"].map(palette)g = sns.clustermap(expr.loc[top_var], z_score=0, cmap="RdBu_r", center=0, vmin=-2.5, vmax=2.5, col_colors=col_colors, figsize=(7, 5), dendrogram_ratio=0.12, cbar_pos=(0.03, 0.83, 0.025, 0.12))handles = [Patch(color=color, label=grp) for grp, color in palette.items()]g.ax_col_dendrogram.legend(handles=handles, ncol=3, loc="lower center", bbox_to_anchor=(0.5, 1.0), frameon=False)g.savefig("outputs/seaborn-clustermap.png", dpi=150, bbox_inches="tight")plt.close(g.figure)
Facets
Section titled “Facets”The figure-level functions catplot, displot, and relplot split the data into panels
with col and row. col_wrap wraps a long row of panels onto several lines.
g = sns.catplot(data=long[long["gene"].isin(de_genes)], x="group", y="log2_cpm", hue="group", palette=palette, col="gene", col_wrap=3, kind="box", height=2.4, aspect=1.1, sharey=False, legend=False)g.set_axis_labels("", "log2 CPM")g.set_titles("{col_name}")g.savefig("outputs/seaborn-catplot.png", dpi=150, bbox_inches="tight")plt.close(g.figure)
Use g.figure for the underlying Matplotlib figure. The older g.fig name still works, but
its docstring marks it as deprecated.
Pair plot
Section titled “Pair plot”pairplot draws every pair of columns, with each column’s distribution on the diagonal.
corner=True drops the mirrored upper triangle.
g = sns.pairplot(wide, vars=["GENE001", "GENE003", "GENE005", "viability"], hue="group", palette=palette, corner=True, height=1.8, plot_kws={"s": 20})g.savefig("outputs/seaborn-pairplot.png", dpi=150, bbox_inches="tight")plt.close(g.figure)
Themes and palettes
Section titled “Themes and palettes”sns.set_theme changes Matplotlib’s global defaults, so call it once at the top of a script.
context scales text and lines for "paper", "notebook", "talk", or "poster". A named
palette returns RGB tuples; as_hex() gives codes you can reuse in a dictionary.
print(sns.color_palette("colorblind", 3).as_hex())print(palette)['#0173b2', '#de8f05', '#029e73']{'control': '#0173b2', 'drug_a': '#de8f05', 'drug_b': '#029e73'}See also
Section titled “See also”- Matplotlib cheatsheet for the Figure and Axes calls underneath every seaborn plot
- Plotly cheatsheet for interactive versions of these plots
- Two-Group Comparison for a box plot with points and a significance bracket
- Multi-Group Comparison for an ANOVA with Tukey brackets
- Clustered Heatmap for a publication clustermap with an annotation bar
- Raincloud Plot for distribution shape, box, and points on one axis
Scientific references
Section titled “Scientific references”Waskom, 2021 describes seaborn for statistical data visualization.
Further reading
Section titled “Further reading”-
The tutorial compares histogram bins, density normalization, kernel density, and cumulative distributions.
-
The tutorial separates data spread from estimate uncertainty and explains bootstrap intervals.