TExcelTAD
Home › Matplotlib › Legends

Legends

When a chart shows more than one series, readers need to know which is which. A legend is the key that pairs each colour or marker with a name. Matplotlib builds it from the label you give each plotted element.

The basic legend

Give every series a label= and call legend():

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

months = np.arange(1, 13)
oslo = [-4, -4, 0, 5, 11, 15, 17, 16, 11, 6, 1, -3]
rome = [8, 9, 12, 15, 19, 24, 27, 27, 23, 18, 13, 9]
cairo = [14, 16, 18, 22, 26, 28, 29, 29, 27, 24, 19, 15]

fig, ax = plt.subplots()
ax.plot(months, oslo, label="Oslo")
ax.plot(months, rome, label="Rome")
ax.plot(months, cairo, label="Cairo")
ax.set(xlabel="Month", ylabel="Mean temperature (°C)")
leg = ax.legend()
plt.show()

print("Legend entries:", [t.get_text() for t in leg.get_texts()])
Legend entries: ['Oslo', 'Rome', 'Cairo']

By default (loc="best") Matplotlib looks for the spot that hides the least data.

Note: Elements without a label, or whose label starts with an underscore (such as "_hidden"), are left out of the legend.

Position

loc takes a position name or code. Combined with bbox_to_anchor you can even place the legend outside the Axes:

loc value
"upper left" "upper center" "upper right"
"center left" "center" "center right"
"lower left" "lower center" "lower right"
"best" (default for Axes) "right"
python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 1, 50)
fig, ax = plt.subplots(figsize=(7, 4), layout="constrained")
for k in range(1, 6):
    ax.plot(x, x ** k, label=f"$x^{k}
quot;) # anchor the legend's "center left" point at (1.02, 0.5) in Axes coordinates ax.legend(loc="center left", bbox_to_anchor=(1.02, 0.5), title="Curve") ax.set_title("Legend outside the plot") plt.show() print("Legend title:", ax.get_legend().get_title().get_text())
Legend title: Curve

In bbox_to_anchor, (0, 0) is the bottom-left and (1, 1) the top-right corner of the Axes, so x = 1.02 is just to the right of it. Constrained layout makes room for the outside legend.

Columns and styling

Argument Effect
ncols Number of columns (entries side by side)
title Heading above the entries
frameon False removes the box
fontsize Size of the entry text
framealpha Transparency of the background
shadow, fancybox Box decorations
markerscale Scale markers relative to the plot

A horizontal legend above the plot works well for a few short labels:

python · try it yourself
import matplotlib.pyplot as plt
import numpy as np

years = np.arange(2015, 2025)
rng = np.random.default_rng(4)
fig, ax = plt.subplots(figsize=(7, 4))
for name in ["Solar", "Wind", "Hydro", "Gas"]:
    ax.plot(years, rng.uniform(5, 20) + rng.normal(0, 2, years.size).cumsum(), label=name)

ax.legend(ncols=4, loc="lower center", bbox_to_anchor=(0.5, 1.0), frameon=False)
ax.set_ylabel("Output (TWh)")
fig.tight_layout()
plt.show()

print("Entries in one row:", [t.get_text() for t in ax.get_legend().get_texts()])
Entries in one row: ['Solar', 'Wind', 'Hydro', 'Gas']

Choosing what goes in the legend

legend() can also take an explicit list of artists (handles) and labels. That lets you reorder entries or include only some of them:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 200)
rng = np.random.default_rng(9)
noisy = np.sin(x) + rng.normal(0, 0.25, x.size)

fig, ax = plt.subplots()
pts = ax.scatter(x, noisy, s=8, color="0.6", label="measurements")
(fit,) = ax.plot(x, np.sin(x), color="C3", lw=2, label="model")
ax.axhline(0, color="k", lw=0.5)         # no label -> not in the legend

ax.legend(handles=[fit, pts], loc="lower left")   # model first
plt.show()

handles, labels = ax.get_legend_handles_labels()
print("Labelled artists:", labels)
Labelled artists: ['measurements', 'model']

Custom legend entries

Sometimes the legend should describe something that isn't a single plotted element, such as colour coding of bars. Build "proxy" artists that are never drawn:

python · try it yourself
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from matplotlib.lines import Line2D

scores = [72, 45, 88, 59, 93, 38]
colors = ["#2a9d8f" if s >= 50 else "#e76f51" for s in scores]

fig, ax = plt.subplots()
ax.bar(range(1, 7), scores, color=colors)
ax.axhline(50, color="k", linestyle="--", lw=1)

legend_items = [
    Patch(color="#2a9d8f", label="Pass"),
    Patch(color="#e76f51", label="Fail"),
    Line2D([0], [0], color="k", linestyle="--", label="Pass mark"),
]
ax.legend(handles=legend_items, loc="upper left")
ax.set(xlabel="Student", ylabel="Score", ylim=(0, 110))
plt.show()

print("Passed:", sum(s >= 50 for s in scores), "of", len(scores))
Passed: 4 of 6

Figure legends

With subplots that share the same series, one legend for the whole figure avoids repetition: fig.legend(...). It collects labelled artists from all Axes (use handles/labels to pick a single set).

Test yourself

What must you do so a line appears in the legend?

  1. Give it a colour
  2. Pass label="..." when plotting it
  3. Call plt.show() first
  4. Use plt.legend(line)

Which arguments place a legend outside the right edge of an Axes?

  1. loc="outside"
  2. loc="center left", bbox_to_anchor=(1.02, 0.5)
  3. loc="right", outside=True
  4. position=(2, 0)

What does ax.legend(ncols=3) do?

  1. Shows only 3 entries
  2. Arranges the entries in 3 columns
  3. Creates 3 legends
  4. Sets the font size to 3