Python Charts

Python plotting and visualization demystified

How to Move the Legend in Seaborn (sns.move_legend)

Use sns.move_legend to put a Seaborn legend outside the plot, above it in one row, or below a FacetGrid, without losing the hue title or handles.

To move a Seaborn legend, call sns.move_legend(ax, loc, ...) after plotting. For example, sns.move_legend(ax, "upper left", bbox_to_anchor=(1, 1)) puts the legend just outside the top-right corner of the axes. It works on axes-level plots (scatterplot, histplot, boxplot) and on figure-level grids from relplot, displot, and catplot, and it keeps the legend's title and handles. ax.legend(loc=...) often loses them.

Quick Example

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

# Sample data: home listings in three neighborhoods
rng = np.random.default_rng(42)
n = 360
homes = pd.DataFrame({
    "neighborhood": rng.choice(["Downtown", "Riverside", "Hillcrest"], n, p=[0.3, 0.4, 0.3]),
    "sqft": rng.normal(1600, 450, n).clip(600, 3200).round(),
})
base = homes["neighborhood"].map({"Downtown": 380, "Riverside": 260, "Hillcrest": 310})
homes["price_k"] = (base * homes["sqft"] / 1000 + rng.normal(0, 60, n)).round()
homes["property_type"] = rng.choice(["Condo", "Townhouse", "Single family"], n)

palette = {"Downtown": "#be123c", "Riverside": "#0369a1", "Hillcrest": "#ca8a04"}

fig, ax = plt.subplots(figsize=(8, 5))
sns.scatterplot(data=homes, x="sqft", y="price_k", hue="neighborhood",
                palette=palette, alpha=0.75, ax=ax)
sns.move_legend(ax, "upper left", bbox_to_anchor=(1, 1))
ax.set(xlabel="Square feet", ylabel="Price ($k)", title="Listing price vs size")

Seaborn scatter plot of listing price versus square feet colored by neighborhood, with the legend moved outside the plot to the right

The scatter plot no longer has a legend covering the Downtown points in the top-right corner. The legend sits to the right of the axes, with its neighborhood title intact. The code targets Seaborn 0.13. move_legend was added in 0.11.2.

How loc and bbox_to_anchor Work Together

move_legend takes the same positioning arguments as Matplotlib's legend():

  • bbox_to_anchor=(x, y) is a point in axes coordinates. (0, 0) is the bottom-left corner of the axes and (1, 1) the top-right. Values outside 0–1 are outside the axes.
  • loc says which corner of the legend box is pinned to that point.

So loc="upper left", bbox_to_anchor=(1, 1) pins the legend's upper-left corner to the axes' top-right corner, and the legend hangs off to the right. Some useful placements:

Placement loc bbox_to_anchor
Outside, right, top-aligned "upper left" (1, 1)
Outside, right, centered "center left" (1, 0.5)
Above the plot, centered "lower center" (0.5, 1)
Below the plot, centered "upper center" (0.5, -0.15)
Inside, best spot "best" omit it

Without bbox_to_anchor, loc just picks a spot inside the axes, such as sns.move_legend(ax, "lower right").

A legend outside the axes can get cut off when you save the figure. Save with fig.savefig("plot.png", bbox_inches="tight") so the image expands to include it. The Matplotlib savefig post explains why.

Put the Legend Above the Plot in One Row

For a handful of categories, a single horizontal row above the plot often reads better than a box on the side, and the plot keeps its full width. Pass ncol for the number of columns, and any other legend() keyword arguments to restyle it while you're at it:

fig, ax = plt.subplots(figsize=(8, 5))
sns.histplot(data=homes, x="price_k", hue="neighborhood", palette=palette,
             multiple="stack", bins=24, ax=ax)
sns.move_legend(ax, "lower center", bbox_to_anchor=(0.5, 1), ncol=3,
                title=None, frameon=False)
ax.set(xlabel="Price ($k)", ylabel="Listings")

Stacked Seaborn histogram of listing prices by neighborhood with a frameless one-row legend centered above the plot

title=None drops the "neighborhood" heading and frameon=False removes the border. The legend becomes a single row of three entries above the stacked histogram.

Why Not Just Use ax.legend()?

With Matplotlib you'd normally write ax.legend(loc=...). On a Seaborn plot, that rebuilds the legend from the artists' labels, and Seaborn doesn't always put labels on its artists. For histplot, kdeplot, and several others, the call finds nothing:

ax = sns.histplot(data=homes, x="price_k", hue="neighborhood")
ax.legend(loc="upper left")
# UserWarning: No artists with labels found to put in legend.

You get an empty legend. For plots where it does work, the hue title is usually lost. move_legend avoids both problems because it copies the existing legend's handles, labels, and title into a new legend at the new spot and then removes the old one.

Approach Keeps title and handles Works with histplot/kdeplot Works with FacetGrid
sns.move_legend(obj, loc, ...) Yes Yes Yes
ax.legend(loc=...) Often no No No
plt.legend(...) Often no No No

Move the Legend on relplot, displot, and catplot

Figure-level functions return a FacetGrid, and the legend belongs to the figure rather than any one axes. Pass the grid itself to move_legend. Here the bbox_to_anchor coordinates are fractions of the whole figure:

g = sns.relplot(data=homes, x="sqft", y="price_k", hue="property_type",
                col="neighborhood", palette="viridis", alpha=0.8,
                height=3.6, aspect=1)
sns.move_legend(g, "upper center", bbox_to_anchor=(0.5, 0.02), ncol=3,
                title="Property type", frameon=False)
g.set_axis_labels("Square feet", "Price ($k)")
g.savefig("listings.png", bbox_inches="tight")

Three Seaborn relplot facets of price versus square feet, one per neighborhood, with a shared property type legend centered below the panels

The shared "Property type" legend now sits centered under all three panels. The grid still reserves the space on the right where the legend used to be. bbox_inches="tight" crops it off when saving (Jupyter's inline display does the same), or you can call g.figure.subplots_adjust(right=0.98) to reclaim it on screen.

move_legend also accepts a Matplotlib Figure if the legend was added with fig.legend().

Change Legend Labels, Font Size, and Title While Moving It

Every keyword argument except loc and labels is passed straight to Matplotlib's legend(), so you can restyle the legend in the same call:

fig, ax = plt.subplots(figsize=(8, 5))
sns.scatterplot(data=homes, x="sqft", y="price_k", hue="neighborhood",
                palette=palette, ax=ax)
sns.move_legend(
    ax, "center left", bbox_to_anchor=(1, 0.5),
    title="Area",
    labels=["Hillcrest (north)", "Riverside (east)", "Downtown (core)"],
    fontsize=9, title_fontsize=10, markerscale=1.4,
)

labels= was added in Seaborn 0.13 and must have the same length as the existing legend, in the same order. Check the current order first with [t.get_text() for t in ax.get_legend().get_texts()]. On older versions, rename the values in the DataFrame column instead. To control the order of the entries, set hue_order in the plotting call. For more styling options, see Change the Legend Title and Font Size in Matplotlib.

Remove the Legend Instead

Pass legend=False to the plotting function, or remove an existing legend:

sns.scatterplot(data=homes, x="sqft", y="price_k", hue="neighborhood", legend=False)

# or, after the fact
ax.get_legend().remove()

For figure-level plots, use legend=False in relplot()/displot()/catplot(), or call g.legend.remove().

Practical Tips

  • Call move_legend after the plot is drawn and before savefig().
  • Save with bbox_inches="tight" whenever the legend is outside the axes.
  • For two or three categories, a frameless one-row legend above the plot (ncol=len(categories), frameon=False) is usually the cleanest layout.
  • move_legend raises ValueError: ... has no legend attached if the plot has no legend, for example when there's no hue or legend=False was set.
  • The same placement ideas apply to plain Matplotlib. See Move the Matplotlib Legend Outside the Plot Box.

Similar Topics