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 prints No 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.
  • Placing the legend outside the plot box (loc + bbox_to_anchor + bbox_inches="tight"):
    • Use loc to choose which corner of the legend box attaches to the (x, y) axes fraction specified by bbox_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!
      
  • ncols= vs. legacy ncol= (Matplotlib 3.6+):
    • Matplotlib 3.6 standardized the multi-column parameter to ncols=2 (matching plt.subplots(ncols=2)). Older ncol=2 still works as an alias, but ncols= is the modern recommended keyword.
  • 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")
      
  • 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())
      
  • Resizing marker icons inside the legend (markerscale=):
    • Scatter plots with tiny points (s=5) often produce barely visible dots in the legend. Pass markerscale=2.5 inside ax.legend(...) to enlarge legend markers independently of the plot markers.

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.