legend() (Matplotlib)
ax.legend() adds a key to a plot that maps each line, marker, or bar to its label, so readers can tell multiple series apart. It uses the label you assigned to each plotted element.
Matplotlib
The clean workflow is to pass label='...' when you plot each series, then call ax.legend() with no arguments; Matplotlib collects the labels automatically and builds the key. You can also pass the labels explicitly to legend() if you didn't set them at plot time.
The loc argument positions the box — 'best' lets Matplotlib find the spot with least overlap, or you can pin it with 'upper right', etc. To move it outside the Axes entirely, combine loc with bbox_to_anchor. ncol spreads entries across multiple columns.
If a legend appears empty or warns about no labeled artists, the usual cause is forgetting the label= argument on the plot calls. legend() returns the Legend object for further tweaking.
Syntax
ax.plot(x, y, label='series'); ax.legend(loc='best')Examples
Python
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2], [3, 4], label="line")
leg = ax.legend()
print(type(leg).__name__)Output:
Legend