Seaborn for Statistical Plots: Tidy Data, Facets, and the Objects API
Learn seaborn with tested code: tidy data, axes-level vs figure-level plots, heatmaps, the objects API, and how 0.13.2 runs on pandas 3 and Matplotlib 3.11.

Learn seaborn with tested code: tidy data, axes-level vs figure-level plots, heatmaps, the objects API, and how 0.13.2 runs on pandas 3 and Matplotlib 3.11.

Seaborn is a Python library for statistical charts. Its official docs call it "a Python data visualization library based on matplotlib" that "provides a high-level interface for drawing attractive and informative statistical graphics." You hand it a DataFrame and name the columns; it handles grouping, aggregation, colors, and legends.
The newest release is seaborn 0.13.2, published in January 2024, and the package logged 30,999,259 downloads in the last month as of 3 December 2026. Every code block in this guide ran on Python 3.15.2 with seaborn 0.13.2, Matplotlib 3.11.2, and pandas 3.1.2.
It runs from tidy data and your first plot to faceted grids, the objects interface, and the warnings 0.13.2 raises on current pandas and Matplotlib.
scatterplot() return a Matplotlib Axes, so everything you know about Axes still applies.DataFrame.melt() first.relplot(), displot(), catplot()) build multi-panel grids from one call. Use plt.subplots() with axes-level functions when you need a custom layout.boxplot() and the objects interface raise deprecation warnings that scripts hide by default.Seaborn turns a DataFrame into a statistical chart in one function call. You assign columns to roles such as x, y, hue, col, and size, and seaborn groups the rows, computes means, confidence intervals, histograms, or density curves, and draws the result with Matplotlib.
The introduction describes a "dataset-oriented, declarative API" that lets you focus on what the elements of a plot mean instead of how to draw them. The same tutorial shows a plot of five variables from one relplot() call, where plain Matplotlib would need a loop over groups.

Seaborn is free and open source under the BSD-3-Clause license, and Michael Waskom created it. If you are new to the layer underneath, start with our Matplotlib guide: seaborn's axes-level charts are Matplotlib Axes you can keep editing.
For exploratory analysis, seaborn covers the chart types you reach for most: distributions, group comparisons, relationships, regressions, and correlation matrices. It pairs naturally with the Python data analysis workflow and with the tests in our Python statistics guide.
The release picture matters if you install it today. The 0.13 series shipped in September 2023, December 2023, and January 2024, and no newer version has reached PyPI since. Development continues on GitHub, where the main branch merged pandas 3 fixes in December 2025 and Python 3.15 support in October 2026.
Three ideas explain almost every seaborn behavior: the shape of your data, the level of the function you call, and the Matplotlib objects underneath.
python -m venv .venv
source .venv/bin/activate
pip install -q seaborn==0.13.2 matplotlib==3.11.2 pandas==3.1.2 numpy==2.5.5 scipy==1.18.1
python -c "import seaborn, matplotlib, pandas; print(seaborn.__version__, matplotlib.__version__, pandas.__version__)"0.13.2 3.11.2 3.1.2The installing page lists NumPy, pandas, and Matplotlib as the mandatory dependencies, and SciPy, statsmodels, and fastcluster as optional. SciPy is pinned here because clustermap() needs it; pip install seaborn[stats] pulls SciPy and statsmodels together. NumPy 2.5.5 requires Python 3.12, so this pinned set needs Python 3.12 or newer even though seaborn itself declares Python 3.8+.
If import seaborn fails with "No module named seaborn" right after installing, the docs point to multiple Python installations and suggest python -m pip install seaborn. Our uv guide covers uv as an alternative to venv and pip.
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme(style="whitegrid")
penguins = sns.load_dataset("penguins")
print(penguins.shape)
print(penguins.columns.tolist())
ax = sns.scatterplot(
data=penguins,
x="flipper_length_mm",
y="body_mass_g",
hue="species",
)
ax.set(xlabel="Flipper length (mm)", ylabel="Body mass (g)")
ax.figure.savefig("first_seaborn.png", dpi=150, bbox_inches="tight")
print(type(ax).__name__)(344, 7)
['species', 'island', 'bill_length_mm', 'bill_depth_mm', 'flipper_length_mm', 'body_mass_g', 'sex']
AxesThe call returned a plain Matplotlib Axes, which is why ax.set() and ax.figure.savefig() work. In a script, call plt.show() to open a window; in Jupyter Notebook the chart appears inline.
load_dataset() downloads example CSVs from the seaborn-data repository on GitHub and "requires internet." It caches files after the first download, and the docs say it "is not necessary for normal usage," so in real work you pass your own DataFrame. Developers on YouTube who teach seaborn, such as NeuralNine, open their tutorials by loading these example datasets, which is why so many snippets assume tips or penguins.
The data structures tutorial defines long-form data in two rules: "Each variable is a column" and "Each observation is a row." It advises: "When possible, try to represent your data with a long-form structure when embarking on serious analysis." Spreadsheet exports are usually wide, with one column per group, so you reshape before plotting.
import pandas as pd
import seaborn as sns
wide = pd.DataFrame(
{
"month": ["Jan", "Feb", "Mar", "Apr"],
"free": [120, 135, 160, 172],
"pro": [30, 34, 41, 47],
"team": [8, 9, 12, 15],
}
)
long = wide.melt(id_vars="month", var_name="plan", value_name="signups")
print(long.shape)
print(long.head(5).to_string(index=False))
ax = sns.lineplot(data=long, x="month", y="signups", hue="plan", marker="o")
ax.figure.savefig("signups_by_plan.png", dpi=150, bbox_inches="tight")
print(sorted(long["plan"].unique()))(12, 3)
month plan signups
Jan free 120
Feb free 135
Mar free 160
Apr free 172
Jan pro 30
['free', 'pro', 'team']Four rows by three plan columns became 12 rows with a plan column, and hue="plan" turned that column into three colored lines with a legend. Seaborn can plot the wide table directly, but the tutorial notes that wide-form pandas data limits you to "no more than three" variables. Long-form data lets you add style, size, or col later without reshaping again.
The function overview splits seaborn into two kinds of functions. Axes-level functions plot onto one Matplotlib Axes, return it, and accept ax=. Figure-level functions manage a whole figure through a seaborn object, usually a FacetGrid, and each module has one: relplot(), displot(), and catplot().
The API reference groups the functions by module:
Module | Figure-level | Axes-level functions it wraps |
|---|---|---|
Relational |
|
|
Distributions |
|
|
Categorical |
|
|
Regression |
|
|
Multi-view |
| combine several of the above |
The docs "generally recommend" figure-level functions for most applications. The exception is "a complex, standalone figure that composes multiple different plot kinds," where you set up the figure with Matplotlib and fill it with axes-level calls.
Most analysis questions map to four plot families: how values are distributed, how groups compare, how two variables relate, and how many variables correlate. The examples below cover each one with output you can check.
import matplotlib.pyplot as plt
import seaborn as sns
penguins = sns.load_dataset("penguins")
fig, axs = plt.subplots(1, 2, figsize=(10, 4), layout="constrained")
sns.histplot(data=penguins, x="flipper_length_mm", hue="species", ax=axs[0])
sns.violinplot(data=penguins, x="species", y="body_mass_g", hue="sex",
split=True, inner="quart", ax=axs[1])
axs[0].set_title("Flipper length by species")
axs[1].set_title("Body mass by species and sex")
fig.savefig("axes_level.png", dpi=150)
print(len(fig.axes), [type(a).__name__ for a in axs])2 ['Axes', 'Axes']
This is the composite-figure case the docs describe. Each axes-level call drew into the Axes you passed with ax=, so a histogram and a violin plot share one figure. The split=True option, generalized in 0.13.0, draws half violins per hue level, and inner="quart" marks the quartiles.
import seaborn as sns
penguins = sns.load_dataset("penguins")
g = sns.displot(
data=penguins,
x="flipper_length_mm",
col="species",
height=3,
aspect=1.2,
)
g.set_axis_labels("Flipper length (mm)", "Count")
g.savefig("displot_facets.png", dpi=150)
print(type(g).__name__, g.axes.shape)
print([round(float(v), 1) for v in g.figure.get_size_inches()])FacetGrid (1, 3)
[10.8, 3.0]One call drew three histograms, one per species, and returned a FacetGrid instead of an Axes. The height and aspect parameters size each subplot, not the whole figure: the docs define width = height * aspect, so three 3.6-inch-wide panels make a 10.8 by 3 inch figure. Add a fourth facet and the figure grows instead of squeezing the panels.
Figure-level functions "own" their figure, so passing ax= does not place them inside your grid. The FAQ says most of them warn and ignore ax=; switch to the axes-level function when you need that control. To set an exact size for either kind, the FAQ suggests obj.figure.set_size_inches(...) after plotting.
import seaborn as sns
tips = sns.load_dataset("tips")
ax = sns.barplot(data=tips, x="day", y="total_bill", errorbar=("ci", 95), seed=0)
ax.figure.savefig("bill_by_day.png", dpi=150, bbox_inches="tight")
means = tips.groupby("day", observed=True)["total_bill"].mean().round(2)
print(means.to_string())day
Thur 17.68
Fri 17.15
Sat 20.44
Sun 21.41A seaborn bar plot shows a mean with a bootstrapped confidence interval, not a count or a sum. The barplot defaults are estimator="mean" and errorbar=("ci", 95), and seed=0 makes the bootstrap repeatable. The errorbar API, introduced in v0.12, also accepts "se" for standard error and "sd" for standard deviation.
The bar heights are the four means printed above. Seaborn does not hand them back: the FAQ calls an API for its computed statistics "explicitly considered out of scope," so the groupby() line is how you get numbers for a report. For the significance tests behind those comparisons, see our Python statistics guide.
import seaborn as sns
penguins = sns.load_dataset("penguins")
numeric = penguins.select_dtypes("number")
corr = numeric.corr().round(2)
print(corr.loc["flipper_length_mm", "body_mass_g"])
ax = sns.heatmap(corr, annot=True, cmap="vlag", vmin=-1, vmax=1, square=True)
ax.figure.savefig("penguin_corr.png", dpi=150, bbox_inches="tight")
print(corr.shape)0.87
(4, 4)heatmap() colors a matrix you already computed, so the 0.87 correlation between flipper length and body mass is a pandas number first and a colored cell second. Setting vmin=-1 and vmax=1 with the diverging vlag map keeps zero in the middle of the color scale, which makes negative and positive correlations easy to tell apart.
The objects interface arrived in seaborn 0.12 as "a completely new interface for making seaborn plots." Instead of choosing a chart function, you declare the data mappings in so.Plot() and add layers: a Mark (what to draw) plus optional Stats (how to transform the data) and Moves (how to adjust positions).
import seaborn as sns
import seaborn.objects as so
penguins = sns.load_dataset("penguins").dropna()
p = (
so.Plot(penguins, x="bill_length_mm", y="bill_depth_mm", color="species")
.add(so.Dot(alpha=0.6))
.add(so.Line(), so.PolyFit(order=1))
.label(x="Bill length (mm)", y="Bill depth (mm)")
)
p.save("objects_plot.png", dpi=150, bbox_inches="tight")
print(type(p).__name__, len(penguins))Plot 333
The first layer draws the 333 complete rows as dots; the second fits a straight line per species with so.PolyFit(order=1). Because color="species" sits in so.Plot(), every layer inherits it. The docs call these methods "fully declarative": each one updates a plot spec, and nothing renders until you save, show, or display it.
The docs are candid about its status: "The objects interface is currently experimental and incomplete. It is stable enough for serious use, but there certainly are some rough edges and missing features." Version 0.13.0 added theme and display configuration and layer legends through a label parameter in Plot.add().
Need | Classic functions | Objects interface |
|---|---|---|
Quick exploratory chart |
| Works, but more typing |
Layering marks and fits on one plot | Several calls on the same Axes |
|
Joint plots with marginal axes, clustered heatmaps |
| No matching mark in 0.13.2 |
Stable API for production reports | Mature, documented in every tutorial | Marked experimental |
Use the classic functions for day-to-day analysis and reach for so.Plot when you want to build a chart layer by layer. The two coexist, so you can mix them in one project.
Most seaborn tutorials were written before pandas 3 and Matplotlib 3.11 shipped. We ran 19 common seaborn calls on Python 3.15.2 with pandas 3.1.2 and Matplotlib 3.11.2, from scatterplot() to clustermap() and the objects interface, and every call drew its chart. Two of them raised deprecation warnings.
import warnings
import matplotlib
import pandas as pd
import seaborn as sns
import seaborn.objects as so
print(sns.__version__, matplotlib.__version__, pd.__version__)
penguins = sns.load_dataset("penguins")
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
sns.boxplot(data=penguins, x="species", y="body_mass_g")
so.Plot(penguins, x="bill_length_mm", y="bill_depth_mm").add(so.Dot()).plot()
for text in sorted({f"{w.category.__name__}: {str(w.message).split('. ')[0]}" for w in caught}):
print(text)0.13.2 3.11.2 3.1.2
MatplotlibDeprecationWarning: vert: bool was deprecated in Matplotlib 3.11 and will be removed in 3.13
Pandas4Warning: The copy keyword is deprecated and will be removed in a future versionBoth warnings are DeprecationWarning subclasses raised inside library code.
Python's default warning filter shows a DeprecationWarning only when your script's own top-level code triggers it, so a plain script prints nothing, while pytest displays them from third-party libraries by default. The first comes from seaborn passing vert= to Matplotlib's bxp(), which the Matplotlib 3.11 API changes deprecate in favor of orientation. The second comes from the objects interface calling pd.concat() with copy=False, a keyword pandas 3 deprecates.
Nothing breaks today, and you cannot fix either warning from your own code because both originate inside seaborn 0.13.2. The practical move is to pin Matplotlib below 3.13 in projects that use boxplot() or catplot(kind="box") until a seaborn release with the fix ships, and to pin pandas in shared environments.
Avoid silencing all warnings globally to hide them. Filter by category and module, for example warnings.filterwarnings("ignore", category=DeprecationWarning, module="seaborn"), so warnings from your own code still reach you.
Seaborn 0.13.0 added provisional support for other DataFrame libraries such as polars through the dataframe interchange protocol, converting them to pandas internally. With polars 2.2.0 that path no longer works, so convert first.
pip install -q polars==2.2.0 pyarrow==26.0.1import polars as pl
import seaborn as sns
df = pl.DataFrame({"plan": ["free", "pro", "team"], "signups": [172, 47, 15]})
print(hasattr(df, "__dataframe__"))
try:
sns.barplot(data=df, x="plan", y="signups")
except TypeError as err:
print("TypeError:", str(err).split(",")[0])
ax = sns.barplot(data=df.to_pandas(), x="plan", y="signups")
print(type(ax).__name__)False
TypeError: Data source must be a DataFrame or Mapping
AxesSeaborn 0.13.2 recognizes non-pandas frames only through the dataframe interchange protocol, and the first printed line shows the polars 2.2.0 DataFrame does not implement it, so seaborn rejects it. df.to_pandas() needs pyarrow installed. If polars is your main DataFrame library, our polars guide and Polars vs pandas comparison cover when the conversion cost matters.
Two everyday tasks trip people up: making charts look consistent, and pulling the numbers behind a chart into a report.
sns.set_theme() "changes the global defaults for all plots using the matplotlib rcParams system." Called with no arguments, it applies seaborn's default theme: context notebook, style darkgrid, palette deep. Without it, the docs say seaborn plots use the current Matplotlib rcParams.
The aesthetics tutorial lists five preset styles and four contexts:
Parameter | Default | Common choices |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
The theme also applies to plain Matplotlib charts in the same session, which keeps a notebook consistent. Call it once at the top of a script or notebook rather than per chart.
import seaborn as sns
iris = sns.load_dataset("iris").drop(columns="species")
g = sns.clustermap(iris.corr(), annot=True, cmap="mako")
g.savefig("iris_clustermap.png", dpi=150)
print(g.data2d.round(2).to_string())
print(g.dendrogram_row.reordered_ind)
try:
sns.clustermap(iris.corr(), return_cluster=True)
except AttributeError as err:
print("AttributeError:", err) sepal_width sepal_length petal_length petal_width
sepal_width 1.00 -0.12 -0.43 -0.37
sepal_length -0.12 1.00 0.87 0.82
petal_length -0.43 0.87 1.00 0.96
petal_width -0.37 0.82 0.96 1.00
[1, 0, 2, 3]
AttributeError: QuadMesh.set() got an unexpected keyword argument 'return_cluster'A r/learnpython poster wanted "the raw numerical matrix that can be seen when annot=True." One reply suggested a return_cluster=True argument, which does not exist: the last line shows the error. The returned ClusterGrid already holds the answer in g.data2d, and the clustermap docs point to dendrogram_row.reordered_ind for the row order.
Wide tables work for quick looks, but each function can make only one kind of wide-form plot. Reshape with melt() first so hue, style, and col are columns you can assign.
catplot(ax=ax) does not draw into your Axes; figure-level functions create their own figure. Use boxplot(), violinplot(), or another axes-level function when you build a grid with plt.subplots().
barplot() shows the mean and a confidence interval by default. Use countplot() for counts, or countplot(stat="percent"), a 0.13.0 addition, for shares.
Since 0.13.0, categorical plots use a single color unless you assign hue, and passing palette without hue is deprecated. Assign a redundant hue, such as boxplot(data=df, x="day", y="tip", hue="day"), to get one color per group.
load_dataset() needs internet access and exists for examples. Read your own data with pd.read_csv() or pd.read_parquet() in production scripts and CI.

Learn Matplotlib the way its docs suggest: the Axes API, subplots, styles that don't look dated, and tested 3.11.2 code for the changes that break old snippets.

DuckDB vs SQLite tested in Python 3.15.2 on 1,000,000 rows: one wins aggregates by about 100x, the other wins lookups and inserts. Code and verdict inside.

DuckDB runs SQL on Parquet, CSV, and pandas frames inside Python. Tested DuckDB 2.0.1 code, the 2.0 changes that break 1.x scripts, and when to skip it.