Seaborn Objects Interface: A Guide to so.Plot

Build charts with seaborn.objects: marks, stats, and moves in so.Plot layers, plus scales, labels, facets, themes, Matplotlib customization, and saving.

The Seaborn objects interface builds a chart in layers: so.Plot() maps columns to x, y, and color, and each .add() call draws a mark such as dots, bars, or a line. Import it with import seaborn.objects as so.

Quick Example

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import seaborn.objects as so

# Sample data: 240 apartment rental listings
rng = np.random.default_rng(97)
n = 240
area = rng.choice(["Riverside", "Midtown", "Hillcrest"], n, p=[0.3, 0.45, 0.25])
size = rng.uniform(30, 110, n)
per_m2 = pd.Series(area).map({"Riverside": 19, "Midtown": 23, "Hillcrest": 15}).to_numpy()
rent = 350 + per_m2 * size + rng.normal(0, 140, n)
flats = pd.DataFrame({
    "area": area,
    "size": size.round(),
    "rent": rent.round(-1),
    "furnished": rng.choice(["Furnished", "Unfurnished"], n, p=[0.35, 0.65]),
})
colors = {"Riverside": "#0284c7", "Midtown": "#db2777", "Hillcrest": "#65a30d"}

(
    so.Plot(flats, x="size", y="rent", color="area")
    .add(so.Dots(pointsize=6))                   # layer 1: the listings
    .add(so.Line(linewidth=3), so.PolyFit(1))    # layer 2: a fitted line per area
    .scale(color=colors)
    .label(x="Size (m²)", y="Monthly rent ($)", color="Area",
           title="Rent rises fastest with size in Midtown")
    .layout(size=(8, 5), extent=(0, 0, 0.82, 1))          # room for the legend
    .show()
)

Seaborn objects scatter plot of rent against apartment size with one fitted line per area, steepest for Midtown

The code targets Seaborn 0.13; the interface first appeared in Seaborn 0.12. With pandas 3, Seaborn 0.13.2 can emit a Pandas4Warning about the copy keyword. It comes from inside Seaborn and does not affect the chart.

Marks, Stats, and Moves

Every layer is .add(mark, stat, move), and only the mark is required.

Part What it does Examples
Mark Draws something Dot, Dots, Line, Path, Bar, Bars, Area, Band, Range, Text
Stat Transforms the data first Count, Agg, Est, Hist, KDE, PolyFit, Perc
Move Adjusts positions Dodge, Stack, Jitter, Shift

Norm is also available to rescale values, for example to percentages.

Each method returns a new Plot, so you can save a base chart in a variable and add different layers to it. In Jupyter the last expression displays itself. In a script, end the chain with .show().

Make a Bar Chart with Count, Dodge, and Stack

so.Count() counts rows in each category. Add so.Dodge() to put the color groups side by side.

(
    so.Plot(flats, x="area", color="furnished")
    .add(so.Bar(), so.Count(), so.Dodge())
    .scale(color=["#7c3aed", "#c4b5fd"])
    .label(x="", y="Listings", color="")
    .layout(size=(8, 4.2), extent=(0, 0, 0.82, 1))
    .show()
)

Side by side bars counting furnished and unfurnished listings in each area

Swap so.Dodge() for so.Stack() to stack the groups.

(
    so.Plot(flats, x="area", color="furnished")
    .add(so.Bar(), so.Count(), so.Stack())
    .scale(color=["#7c3aed", "#c4b5fd"])
    .label(x="", y="Listings", color="")
    .layout(size=(8, 4.2), extent=(0, 0, 0.82, 1))
    .show()
)

Stacked bars counting furnished and unfurnished listings in each area

Add Value Labels with so.Text

so.Text needs a column to use as the label, so compute the summary with pandas and plot it directly.

medians = flats.groupby("area", as_index=False)["rent"].median()
medians["label"] = medians["rent"].map("${:,.0f}".format)

(
    so.Plot(medians, x="area", y="rent", text="label")
    .add(so.Bar(color="#0f766e"))
    .add(so.Text(color="#111827", valign="bottom"))
    .limit(y=(0, medians["rent"].max() * 1.12))
    .label(x="", y="Median rent ($)")
    .layout(size=(7, 4.2))
    .show()
)

Bar chart of median rent by area with a dollar label on top of each bar

Show Points, Means, and Intervals Together

Layers can use different stats and moves. Here so.Jitter spreads the raw points, so.Agg finds each mean, and so.Est computes a 95% bootstrap confidence interval.

flats["rent_per_m2"] = flats["rent"] / flats["size"]

(
    so.Plot(flats, x="area", y="rent_per_m2")
    .add(so.Dots(color="#94a3b8"), so.Jitter(0.5, seed=1))
    .add(so.Range(color="#111827", linewidth=3), so.Est(errorbar=("ci", 95), seed=1),
         so.Shift(x=0.34))
    .add(so.Dot(color="#111827", pointsize=9), so.Agg("mean"), so.Shift(x=0.34))
    .label(x="", y="Rent per m² ($)")
    .layout(size=(8, 4.5))
    .show()
)

Jittered rent per square metre points for each area with the mean and confidence interval drawn beside them

Set seed on Jitter and Est to get the same picture on every run.

Histograms and Density Curves

so.Hist bins the data. By default the groups are normalized together; common_norm=False scales each group on its own, which compares shapes when group sizes differ.

(
    so.Plot(flats, x="rent", color="area")
    .add(so.Area(alpha=0.35), so.KDE(common_norm=False))
    .scale(color=colors)
    .label(x="Monthly rent ($)", y="Density", color="Area")
    .layout(size=(8, 4.2), extent=(0, 0, 0.82, 1))
    .show()
)

Overlapping filled density curves of rent for the three areas

Use so.Bars() with so.Hist(binwidth=200) for a histogram.

Small Multiples with facet and pair

.facet() makes one panel per category from col, row, or both, and wrap= starts a new line of panels.

(
    so.Plot(flats, x="rent")
    .facet(col="area", order=["Hillcrest", "Riverside", "Midtown"])
    .add(so.Bars(color="#0284c7"), so.Hist(binwidth=200))
    .label(x="Rent ($)", y="Listings")
    .layout(size=(10, 3.4))
    .show()
)

Three histograms of rent, one panel per area, with shared axes

Panels share axes by default; .share(x=False) or .share(y=False) frees them. .pair() instead repeats the chart for several columns:

(
    so.Plot(flats, y="rent", color="area")
    .pair(x=["size", "rent_per_m2"])
    .add(so.Dots())
    .scale(color=colors)
    .label(x0="Size (m²)", x1="Rent per m² ($)", y="Rent ($)", color="Area")
    .layout(size=(9, 3.8), extent=(0, 0, 0.82, 1))
    .show()
)

Rent plotted against size and against rent per square metre in two panels

Keep the Legend Off the Data

When you call .show(), Seaborn 0.13 places the legend inside the right edge of the figure, where it can cover data. .layout(extent=(0, 0, 0.82, 1)) confines the panels to the left 82% of the figure and leaves the legend its own space, as in the examples above. The four numbers are left, bottom, right, and top, as fractions of the figure. Reduce 0.82 for longer legend labels.

A plot saved with .save(..., bbox_inches="tight"), or displayed by Jupyter without .show(), puts the legend outside the figure instead, so you can leave extent out.

Control Scales and Tick Formats

.scale() sets how data values map to positions, colors, and sizes.

(
    so.Plot(flats, x="size", y="rent", color="rent_per_m2", pointsize="size")
    .add(so.Dot(alpha=0.8))
    .scale(
        x=so.Continuous().tick(every=20).label(like="{x:.0f} m²"),
        y=so.Continuous().label(like="${x:,.0f}"),
        color="viridis",
        pointsize=(3, 12),
    )
    .label(x="", y="", color="Rent per m²", pointsize="Size")
    .layout(size=(8, 4.8), extent=(0, 0, 0.82, 1))
    .show()
)

Scatter plot with dollar and square metre tick labels, colored by rent per square metre and sized by apartment size

Use x="log" for a log axis, a dictionary or list for categorical colors, and a colormap name for numeric colors.

Change the Theme

so.Plot does not follow sns.set_theme(). Pass a dictionary of Matplotlib settings to .theme(); the Seaborn style functions return one.

(
    so.Plot(flats, x="size", y="rent")
    .add(so.Dots(color="#db2777"))
    .theme({**sns.axes_style("ticks"), **sns.plotting_context("talk"),
            "axes.spines.top": False, "axes.spines.right": False})
    .label(x="Size (m²)", y="Rent ($)")
    .layout(size=(8, 4.8))
    .show()
)

Scatter plot of rent and size with a ticks style, large text, and no top or right border

To change every later objects chart, run so.Plot.config.theme.update(sns.axes_style("whitegrid")).

Customize with Matplotlib and Save

.on() draws into a Matplotlib Axes or figure that you created. Call .plot() to render it, then use any Matplotlib method.

fig, ax = plt.subplots(figsize=(8, 4.5))
(
    so.Plot(flats, x="size", y="rent")
    .add(so.Dots(color="#65a30d"))
    .on(ax)
    .plot()
)
ax.axhline(2000, color="#111827", linestyle="--")
ax.annotate("Budget: $2,000", (30, 2000), xytext=(0, 6), textcoords="offset points")
ax.set(xlabel="Size (m²)", ylabel="Rent ($)")
plt.show()

Objects interface scatter plot with a dashed budget line added using Matplotlib

An Axes target cannot be combined with .facet() or .pair(); pass a figure or subfigure for those. To save without .on():

plot = so.Plot(flats, x="size", y="rent", color="area").add(so.Dots())
plot.save("rents.png", dpi=200, bbox_inches="tight")

bbox_inches="tight" keeps the legend, which sits outside the figure, in the saved file.

Objects Interface or the Function Interface?

Choose so.Plot when Choose sns.scatterplot and friends when
You want to combine stats and marks freely A single function already draws the chart
You are layering several summaries of one dataset You need box, violin, swarm, or boxen plots
You like a chained, grammar-of-graphics style You need heatmaps, clustermap, jointplot, or pairplot
You want regression lines with confidence bands (regplot)

The two can be used in the same script. The objects interface does not replace the functions, and several chart types in the right-hand column have no so mark.

Similar Topics