Skip to content

Seaborn

Seaborn draws statistical charts from a DataFrame and column names: it groups, aggregates, adds confidence intervals and builds legends for you. It draws with Matplotlib, so every ax method from the Matplotlib page works on its charts. Examples use data/customers.csv and data/sensors.csv.

I want to… Use… Example
a theme for every chart sns.set_theme sns.set_theme(style="whitegrid", palette="colorblind")
the distribution of a column sns.histplot sns.histplot(data=df, x="price", bins=30)
a skewed column log_scale=True sns.histplot(data=df, x="price", log_scale=True)
compare distributions of groups hue= + stat="density", common_norm=False sns.histplot(data=df, x="age", hue="churned", stat="density", common_norm=False)
a smooth density sns.kdeplot sns.kdeplot(data=df, x="price", hue="area", fill=True)
cumulative shares sns.ecdfplot sns.ecdfplot(data=df, x="price", hue="area")
the mean per group with a CI sns.barplot, sns.pointplot sns.barplot(data=df, x="plan", y="churned", errorbar=("ci", 95))
counts per category sns.countplot sns.countplot(data=df, y="plan", order=["basic", "standard", "premium"])
distributions per group sns.violinplot, sns.boxenplot, sns.stripplot sns.violinplot(data=df, x="plan", y="charges", inner="quart")
two halves of a violin split=True with a 2-level hue sns.violinplot(..., hue="churned", split=True)
a scatter with color, size and marker sns.scatterplot sns.scatterplot(data=df, x="a", y="b", hue="g", size="n", style="kind")
a mean line with a band sns.lineplot sns.lineplot(data=df, x="month", y="sales", hue="year")
one line per unit, no aggregation units=, estimator=None sns.lineplot(..., units="sensor_id", estimator=None)
a fitted line sns.regplot, sns.lmplot sns.regplot(data=df, x="sqft", y="price", scatter_kws={"alpha": 0.3})
check a fit’s residuals sns.residplot sns.residplot(data=df, x="sqft", y="price", lowess=True)
a table as colors sns.heatmap sns.heatmap(pivot, annot=True, fmt=".0%", cmap="rocket_r")
a correlation matrix sns.heatmap with vmin=-1, vmax=1 sns.heatmap(corr, cmap="vlag", vmin=-1, vmax=1, annot=True)
clustered rows and columns sns.clustermap sns.clustermap(corr, cmap="vlag")
one panel per group figure-level + col=, row= sns.relplot(..., col="region", col_wrap=2)
draw into my Matplotlib grid axes-level + ax= sns.histplot(..., ax=axs[0])
two variables and their margins sns.jointplot sns.jointplot(data=df, x="a", y="b", kind="hex")
all pairs of a few columns sns.pairplot sns.pairplot(df[cols].sample(300, random_state=42), corner=True)
a fixed category order order=, hue_order=, col_order= order=["basic", "standard", "premium"]
one color, no legend color= sns.barplot(..., color="C0")
a palette for categories hue= + palette= sns.barplot(data=df, x="plan", y="v", hue="plan", palette="Set2", legend=False)
move the legend sns.move_legend sns.move_legend(ax, "upper left", bbox_to_anchor=(1, 1))
remove the top and right frame sns.despine sns.despine(), sns.despine(left=True)
bigger fonts for slides sns.set_theme(context=...) context="talk"
save a figure-level chart g.savefig g.savefig("output/grid.png", dpi=150)
Family Axes-level (ax=) Figure-level (col=, row=) Key parameters
distribution histplot, kdeplot, ecdfplot, rugplot displot(kind="hist" | "kde" | "ecdf") bins, binwidth, stat, common_norm, multiple, element, log_scale, bw_adjust, cumulative
categorical: estimates barplot, pointplot, countplot catplot(kind="bar" | "point" | "count") estimator, errorbar, n_boot, seed, order, dodge
categorical: distributions boxplot, violinplot, boxenplot catplot(kind="box" | "violin" | "boxen") inner, split, cut, density_norm, gap, fill
categorical: points stripplot, swarmplot catplot(kind="strip" | "swarm") jitter, dodge, size, alpha
relational scatterplot, lineplot relplot(kind="scatter" | "line") hue, size, style, sizes, markers, estimator, errorbar, units
regression regplot, residplot lmplot order, logistic, lowess, robust, ci, x_bins, scatter_kws, line_kws
matrix heatmap clustermap annot, fmt, cmap, vmin, vmax, mask, linewidths, cbar, square
multi-plot — pairplot, jointplot, FacetGrid, PairGrid, JointGrid vars, hue, corner, kind, diag_kind, height, aspect
Parameter Values Meaning
stat (histplot) "count", "frequency", "density", "probability", "percent" what bar height means
common_norm True (default), False normalize all hue groups together or each on its own
multiple "layer", "stack", "dodge", "fill" how hue groups combine; "fill" = 100% stacked
element "bars", "step", "poly" histogram shape; "step" overlaps well
errorbar ("ci", 95), "se", "sd", ("pi", 50), None interval: bootstrap CI, standard error, standard deviation, percentile
estimator "mean" (default), "median", "sum", a function what one bar or line point shows
inner (violinplot) "box", "quart", "point", "stick", None what is drawn inside each violin
native_scale True keep numeric or date x positions in categorical plots
legend "auto", "brief", "full", False legend detail; False hides it
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
sns.set_theme(style="whitegrid", palette="colorblind") # global: every later chart
customers = pd.read_csv("data/customers.csv")
plans = ["basic", "standard", "premium"]
fig, axs = plt.subplots(1, 2, figsize=(9, 3.6), layout="constrained")
sns.histplot(data=customers, x="monthly_charges", hue="plan", hue_order=plans,
element="step", bins=40, ax=axs[0]) # axes-level: draws into axs[0]
sns.barplot(data=customers, x="contract", y="churned", hue="plan", hue_order=plans,
order=["month-to-month", "one-year", "two-year"],
errorbar=("ci", 95), seed=42, ax=axs[1]) # mean of 0/1 = churn rate
axs[0].set(xlabel="monthly charges (USD)")
axs[1].set(ylabel="churn rate")
axs[1].get_legend().remove() # one legend is enough
print(customers.pivot_table(index="contract", columns="plan", values="churned")
.loc[:, plans].round(3))
plt.show()
Output
plan basic standard premium
contract
month-to-month 0.265 0.262 0.432
one-year 0.064 0.049 0.214
two-year 0.028 0.026 0.052
Left: step histograms of monthly charges form three separate humps by plan, basic near 38 USD, standard near 63 USD and premium near 97 USD. Right: churn-rate bars with 95% error bars: month-to-month churn is about 26% for basic and standard and 43% for premium; one-year churn is 5–6% except 21% for premium; two-year churn stays at 5% or below.
Two axes-level functions in one Matplotlib grid.
Axes-level Figure-level
Functions histplot, barplot, scatterplot, heatmap, … displot, catplot, relplot, lmplot, pairplot, jointplot, clustermap
Returns a Matplotlib Axes a FacetGrid (or PairGrid, JointGrid, ClusterGrid)
Where it draws the current Axes or ax= its own new figure
Panels one col=, row=, col_wrap=
Size plt.subplots(figsize=...) height= (inches per panel), aspect= (width ÷ height)
Legend inside the Axes outside, on the right
Fine-tune ax.set(...) g.set(...), g.set_titles(...), g.axes.flat, g.figure
FacetGrid method or attribute Does
g.set_titles("{col_name}"), "{row_name} | {col_name}" short panel titles
g.set_axis_labels("x label", "y label") labels on the outer panels
g.set(xlim=(0, 100), yscale="log") ax.set(...) on every panel
g.figure.suptitle("...", y=1.03) one title above the grid
g.axes, g.axes.flat, g.axes_dict["premium"] the panels as an array, a flat iterator or a dict
g.map_dataframe(func, x=..., y=...) run any plotting function on each panel’s subset
g.refline(y=0.5) a reference line on every panel
g.tick_params(axis="x", labelrotation=45) ticks on every panel
g.legend, sns.move_legend(g, "upper center", ncols=3) the legend, or move it
g.savefig("output/x.png", dpi=150) save the whole figure
Argument Maps a column to Works in
hue= color almost every function
size= marker size or line width scatterplot, lineplot, relplot
style= marker shape or dash pattern scatterplot, lineplot, relplot
col=, row= separate panels figure-level functions
col_wrap=3 wrap columns onto rows figure-level functions, with col= only
units= one unaggregated line per unit lineplot, relplot(kind="line")
x= and y= swapped horizontal categorical plots sns.barplot(data=df, x="value", y="category")

A numeric hue gets a continuous light-to-dark palette; a text hue gets distinct colors. Convert with df["year"].astype(str) when the numbers are labels.

labels = {0: "stayed", 1: "churned"}
status = customers.assign(status=customers["churned"].map(labels)) # readable legend
g = sns.catplot(data=status, kind="violin", x="plan", y="monthly_charges",
hue="status", hue_order=["stayed", "churned"], split=True,
inner="quart", col="contract",
order=plans, col_order=["month-to-month", "one-year", "two-year"],
height=3, aspect=0.9) # figure-level: returns a FacetGrid
g.set_titles("{col_name}")
g.set_axis_labels("", "monthly charges (USD)")
print(type(g).__name__, g.axes.shape, sorted(g.axes_dict))
plt.show()
Output
FacetGrid (1, 3) ['month-to-month', 'one-year', 'two-year']
Three panels of split violins of monthly charges by plan, one panel per contract, with stayed customers on the left half and churned customers on the right half, as the status legend shows; charges center near 38, 63 and 97 USD for basic, standard and premium, and the churned half sits at most a few dollars higher.
catplot with col= for contracts and hue= split violins for churn.

The relational family draws lines and points. relplot(kind="line") averages the rows at each x and draws a bootstrap confidence band around the mean:

sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])
sensors["hour"] = sensors["timestamp"].dt.hour
sensors["week"] = (sensors["timestamp"].dt.day <= 7).map({True: "May 1–7",
False: "May 8–14"})
g = sns.relplot(data=sensors, kind="line", x="hour", y="temperature_c",
hue="sensor_id", col="week", errorbar=("ci", 95), seed=42,
height=3, aspect=1.4) # band: 95% bootstrap CI of the mean
g.set_titles("{col_name}")
g.set_axis_labels("hour of day", "temperature (°C)")
g.legend.set_title("sensor")
print(sensors.groupby(["week", "sensor_id"])["temperature_c"].mean().unstack().round(1))
plt.show()
Output
sensor_id S1 S2 S3 S4
week
May 1–7 22.1 24.6 22.3 26.0
May 8–14 22.0 24.6 24.7 26.1
Two panels of mean temperature by hour of day for sensors S1 to S4, May 1–7 and May 8–14, each with a narrow confidence band: every sensor is coolest around 2–4 a.m. and warmest near 3–4 p.m.; S4 runs warmest (24 to 28 °C) and S1 coolest (20 to 24 °C); S3 tracks S1 in the first week but runs about 2.5 °C warmer in the second week.
relplot(kind="line") with hue= per sensor, col= per week and a 95% bootstrap band.
Call Effect
sns.set_theme() Seaborn defaults: darkgrid style, deep palette, notebook context
sns.set_theme(style=...) "darkgrid", "whitegrid", "dark", "white", "ticks"
sns.set_theme(context=...) font scale: "paper" < "notebook" < "talk" < "poster"
sns.set_theme(palette=..., font_scale=1.2, rc={...}) default colors, size factor, any rcParams
with sns.axes_style("white"): a style for one block
sns.despine(offset=5, trim=True) remove the top and right spines
sns.reset_defaults() Matplotlib defaults again
Palette Kind Use for
"colorblind", "deep", "muted", "Set2", "tab10" qualitative categories without order
"rocket", "mako", "viridis", "crest" sequential counts, rates; add "_r" to reverse
"vlag", "icefire", "RdBu_r" diverging values around a center, correlations
"light:#0173b2", "dark:salmon" sequential from one color one hue from light or dark to that color
"blend:#7AB,#EDA" blend of two or more colors custom sequential ramps
"ch:s=.25,rot=-.25" cubehelix sequential with even brightness steps
print(sns.color_palette("colorblind", 3).as_hex()) # a list of colors
print(sns.color_palette("light:#0173b2", 3).as_hex()) # a ramp from one color
cmap = sns.color_palette("rocket", as_cmap=True) # a Matplotlib colormap
print(type(cmap).__name__, cmap.N)
Output
['#0173b2', '#de8f05', '#029e73']
['#eff1f3', '#78b2d2', '#0173b2']
ListedColormap 256
daily = sensors.pivot_table(index="sensor_id", columns=sensors["timestamp"].dt.day,
values="vibration_mm_s", aggfunc="mean")
fig, ax = plt.subplots(figsize=(9, 2.8), layout="constrained")
sns.heatmap(daily, annot=True, fmt=".1f", cmap="rocket_r", linewidths=0.5,
cbar_kws={"label": "mm/s"}, ax=ax) # cmap _r: dark = high
ax.set(xlabel="day of May 2024", ylabel="", title="Mean vibration per sensor and day")
print(daily.loc["S4"].tail(4).round(1).to_dict())
plt.show()
Output
{11: 3.3, 12: 5.2, 13: 6.9, 14: 9.0}
Heatmap of mean daily vibration for sensors S1 to S4 over May 1–14: S1, S2 and S3 stay flat near 2.1, 2.8 and 2.0 mm/s, and S4 stays near 3.2 mm/s until May 11, then darkens to 5.2, 6.9 and 9.0 mm/s on May 12–14.
An annotated heatmap of a pivot table.
Old code or symptom Message Use now
ci=95, ci=None FutureWarning: The ci parameter is deprecated errorbar=("ci", 95), errorbar=None
palette= without hue= in barplot, boxplot, countplot, … FutureWarning: Passing palette without assigning hue is deprecated hue=<the x column>, legend=False, or color="C0"
palette= without hue= in histplot UserWarning: Ignoring palette because no hue variable has been assigned color=
scale= in violinplot FutureWarning: The scale parameter has been renamed density_norm="width" (or "area", "count")
sns.boxplot, catplot(kind="box") with Matplotlib 3.11 MatplotlibDeprecationWarning about vert (from inside Seaborn; hidden by default) ax.boxplot(..., orientation="vertical"), sns.violinplot(inner="box") or sns.boxenplot
sns.heatmap(..., center=0) with Matplotlib 3.11 PendingDeprecationWarning about set_bad (hidden by default) symmetric vmin=-v, vmax=v
g.fig still works g.figure (the documented name)
swarmplot with thousands of points UserWarning: 28.3% of the points cannot be placed stripplot(alpha=0.3) or a sample
seaborn.objects (so.Plot) with pandas 3.1 hidden Pandas4Warning about the copy keyword the function interface, or ignore until a Seaborn fix
sns.load_dataset("tips") needs the internet read the course files in data/

New in 0.13: categorical functions accept native_scale=True, log_scale=, formatter=, fill=False and gap=, and hue= works without dodging when it equals x.

Trap Symptom Fix
ax= passed to a figure-level function a UserWarning, and a second figure appears use the axes-level function, or size with height=/aspect=
figsize for relplot, catplot, displot ignored height= and aspect=
sns.set_theme in a module or notebook every later chart changes style call it once at the top; sns.axes_style in a with block for one chart
categories in data order weekdays, months or plans in random order order=, hue_order=, col_order=
numeric hue such as a year a light-to-dark gradient, not distinct colors hue=df["year"].astype(str)
groups of different size in histplot the small group looks flat stat="density", common_norm=False
barplot on raw rows it shows the mean, not the sum estimator="sum" or aggregate first
bootstrap CIs differ between runs error bars move slightly seed=42
barplot and lineplot are slow CIs bootstrap 1,000 times errorbar=None or errorbar="se"
pairplot on many columns or rows slow and unreadable 3–5 columns and a sample of a few hundred rows
a KDE below 0 for prices or ages density where no data can exist cut=0, clip=(0, None) or histplot
two legends in a grid of axes-level plots repeated legends ax.get_legend().remove() or legend=False on all but one
sns.boxplot in a strict warnings setup MatplotlibDeprecationWarning with Matplotlib 3.11 ax.boxplot(orientation=...) or a violin
annotation arrows invisible in a Seaborn theme the default arrow is white on darkgrid arrowprops={"arrowstyle": "->", "color": "0.3"}
heatmap of a large table with annot=True unreadable numbers fewer rows, or no annot