Skip to content

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.

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")

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 plt
import numpy as np
import pandas as pd
import seaborn as sns
from 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 = 200
genes = [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 viability
0 GENE001 S01 7.63 control b1 89.1
1 GENE002 S01 5.49 control b1 89.1
2 GENE003 S01 9.58 control b1 89.1
3 GENE004 S01 8.36 control b1 89.1
4 GENE005 S01 4.22 control b1 89.1

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)

Box plot of GENE001 by group. The control median sits near 7.6 log2 CPM, drug A near 10.1, and drug B near 8.8.

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)

Violin plot of GENE001 by group with dashed quartile lines inside each violin. The control violin spans about 6.4 to 8.7 log2 CPM, drug A about 9.5 to 11, and drug B about 8.5 to 9.8.

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 argument
fig, 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)

Box plot of GENE001 by group with the eight samples of each group drawn as black points over the boxes. The drug B point near 9.8 sits above its whisker and appears once.

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)

Swarm plot of GENE001 by group with points colored by batch. In each group most orange b2 points sit above the blue b1 points.

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)

Grouped box plot of GENE001 with a b1 box and a b2 box inside each group. The b2 median is higher than the b1 median in all three groups, by about 0.4 to 0.8 log2 units.

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)

Two overlaid step histograms with density curves of all 4,800 log2 CPM values, one per batch. Both span about 2.5 to 12.5, and the b2 curve peaks near 7.1, about half a unit right of the b1 peak.

sns.kdeplot draws the curve alone, and sns.ecdfplot draws the cumulative distribution.

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)

Bar plot of mean viability by group with standard deviation error bars. Control is near 89 percent, drug A near 74 percent, and drug B near 81 percent.

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 85
group
control 0 2 6
drug_a 4 4 0
drug_b 0 7 1

Count plot of samples per group and viability band. Control has 2 samples at 75 to 85 percent and 6 above 85. Drug A has 4 at 75 or less and 4 at 75 to 85. Drug B has 7 at 75 to 85 and 1 above 85.

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)

Time course of GENE001 over 24 hours with one line per group and a shaded 95% confidence band. Drug A rises from about 7.7 to 10.0 log2 CPM, drug B rises from about 7.8 to between 8.6 and 8.8, and control stays between 7.2 and 7.6.

errorbar="sd" draws one standard deviation instead, and units="replicate" with estimator=None draws one line per replicate.

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 viability
GENE001 1.00 -0.93
viability -0.93 1.00

Scatter plot of viability against GENE001 expression for 24 samples. The regression line falls from about 95 percent at 6.4 log2 CPM to about 70 percent at 11, with a shaded confidence band that widens at both ends.

sns.lmplot(data=wide, x="GENE001", y="viability", hue="group") fits one line per group.

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.

PCA scores of 24 samples, colored by group, sized by viability, and shaped by batch. PC1, with 23 percent of the variance, puts batch b1 near plus 4 and batch b2 near minus 4. Within each batch, PC2 orders drug A at the top, drug B in the middle, and control at the bottom, and the largest markers are controls.

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)

Annotated heatmap of the mean log2 change against control for six genes. Drug A reads 2.5, 1.5, minus 2.3, minus 1.8, 0.3, and minus 0.4 for GENE001 to GENE006. Drug B reads 1.3, 0.6, minus 1.1, minus 0.9, 1.7, and minus 1.7.

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).index
col_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)

Clustered heatmap of the 10 most variable genes across 24 samples, with a group color bar above the columns and dendrograms on both axes. The 8 drug A samples form one cluster and the 8 drug B samples another, while control splits into clusters of 5 and 3. GENE001 to GENE006 sit among four genes with no simulated effect.

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)

Six box plot panels, one per gene from GENE001 to GENE006, each with its own y axis. GENE001 and GENE002 rise most in drug A, GENE003 and GENE004 fall most in drug A, and GENE005 and GENE006 move most in drug B.

Use g.figure for the underlying Matplotlib figure. The older g.fig name still works, but its docstring marks it as deprecated.

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)

Corner pair plot of GENE001, GENE003, GENE005, and viability, colored by group, with density curves on the diagonal. GENE001 against viability falls in a tight line, and GENE005 separates drug B from the other two groups.

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'}

Waskom, 2021 describes seaborn for statistical data visualization.

  • Seaborn distribution plots

    The tutorial compares histogram bins, density normalization, kernel density, and cumulative distributions.

  • Seaborn error bars

    The tutorial separates data spread from estimate uncertainty and explains bootstrap intervals.