Pass label="..." to each plotting call (ax.plot(..., label="Train")) and call ax.legend() (or plt.legend()), customizing its placement, columns, frame, and typography with arguments such as loc=, bbox_to_anchor=, ncols=, frameon=, and fontsize=—or pass explicit (handles, labels) lists to ax.legend(handles, labels) when you need full control over entry order or custom proxy artists.
Basic Example
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax = plt.subplots(figsize=(7, 4))
# 1. Attach `label=` to every artist you want included in the legend
ax.plot(x, np.sin(x), color="#1f77b4", linewidth=2, label="sin(x)")
ax.plot(x, np.cos(x), color="#ff7f0e", linestyle="--", linewidth=2, label="cos(x)")
# 2. Customize location, layout, typography, and frame styling
ax.legend(
loc="upper right", # Anchor corner inside axes ("best", "upper left", "lower right", etc.)
title="Trig Functions", # Optional legend header
title_fontsize=10,
fontsize=9,
ncols=2, # Arrange entries horizontally across 2 columns (formerly `ncol`)
frameon=True, # Show background box (False = transparent borderless legend)
fancybox=True, # Rounded corners
framealpha=0.9, # Semi-transparent background (0.0 to 1.0)
edgecolor="gray",
shadow=False,
)
ax.set_xlabel("x")
ax.set_ylabel("y")
fig.tight_layout()
plt.show()
Key Details & Edge Cases
- Artists without
label=(or starting with"_") are automatically excluded:- Calling
ax.legend()with no artists labeled printsNo artists with labels found to put in legend. - Prefixing a label with a leading underscore—such as
label="_baseline"—intentionally hides that line from the legend while keeping it plotted.
- Calling
- Placing the legend outside the plot box (
loc+bbox_to_anchor+bbox_inches="tight"):- Use
locto choose which corner of the legend box attaches to the(x, y)axes fraction specified bybbox_to_anchor=(x, y):# Place legend to the right of the axes without overlapping data ax.legend(loc="upper left", bbox_to_anchor=(1.02, 1.0), borderaxespad=0) fig.savefig("chart.png", bbox_inches="tight") # Prevents clipping the outside legend on save!
- Use
ncols=vs. legacyncol=(Matplotlib 3.6+):- Matplotlib 3.6 standardized the multi-column parameter to
ncols=2(matchingplt.subplots(ncols=2)). Olderncol=2still works as an alias, butncols=is the modern recommended keyword.
- Matplotlib 3.6 standardized the multi-column parameter to
- Custom proxy legend entries (
matplotlib.lines.Line2D/matplotlib.patches.Patch):- When a legend entry does not correspond directly to a single plotted artist (for example, highlighting shaded regions, error bands, or grouped categories), pass custom proxy artists directly:
from matplotlib.patches import Patch handles = [Patch(facecolor="steelblue", edgecolor="black", label="Approved Region")] ax.legend(handles=handles, loc="lower left")
- When a legend entry does not correspond directly to a single plotted artist (for example, highlighting shaded regions, error bands, or grouped categories), pass custom proxy artists directly:
- Reordering or deduplicating legend entries (
ax.get_legend_handles_labels()):- When plotting in loops or grouped scatter plots that produce duplicate labels, deduplicate cleanly via a dictionary mapping labels back to handles:
handles, labels = ax.get_legend_handles_labels() by_label = dict(zip(labels, handles)) ax.legend(by_label.values(), by_label.keys())
- When plotting in loops or grouped scatter plots that produce duplicate labels, deduplicate cleanly via a dictionary mapping labels back to handles:
- Resizing marker icons inside the legend (
markerscale=):- Scatter plots with tiny points (
s=5) often produce barely visible dots in the legend. Passmarkerscale=2.5insideax.legend(...)to enlarge legend markers independently of the plot markers.
- Scatter plots with tiny points (
Comparison of Key Matplotlib Legend Customization Parameters
| Parameter | Example Values | Effect on Legend | Best Used When |
|---|---|---|---|
loc= |
"best", "upper left", "lower right", "center" |
Sets placement inside axes (or anchor corner when paired with bbox_to_anchor). |
Positioning the legend cleanly away from plotted curves. |
bbox_to_anchor= |
(1.02, 1.0) or (0.5, -0.15) |
Anchors the legend outside the axes in normalized (x, y) axes coordinates. |
Preventing legends from covering dense data or multi-series plots. |
ncols= |
1 (default), 2, 3 |
Splits legend items across multiple horizontal columns. | Placing a compact horizontal legend above or below a chart. |
frameon= / framealpha= |
frameon=False or framealpha=0.85 |
Toggles background box border or adjusts background transparency. | Blending the legend seamlessly over gridlines or clean minimal figures. |
fontsize= / title= |
fontsize=9, title="Series" |
Sets entry text size and adds a header title above legend items. | Improving legibility and grouping multi-series categories. |
markerscale= / handlelength= |
markerscale=2.0, handlelength=2.5 |
Scales marker icon size or line-segment sample width inside the legend box. | Making small scatter markers or dashed line styles clearly readable. |
You must log in or register to comment.
