Adding a matplotlib legend
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
A legend tells the reader which line, marker, or bar corresponds to each dataset. In Matplotlib, the mechanics are simple, but good legends depend on labeling the right artists and placing the box where it clarifies the chart instead of covering it.
Start With Labels And legend()
The normal pattern is to give each plotted series a label and then call legend() on the axes.
Matplotlib collects labeled artists and builds the legend automatically. If a plotted item has no label, or its label starts with an underscore, it will usually be ignored by automatic legend generation.
The same pattern works for more than line charts. Scatter plots, bars, and many other artist types can participate in the legend as long as they have labels and are attached to the axes you call legend() on.
Control Placement So The Plot Stays Readable
The default legend location is often acceptable, but real charts usually need placement adjustments. The loc argument handles common positions:
If the legend hides important data, place it outside the plotting area:
That is a common pattern for dashboards and dense line plots.
Pass Explicit Handles When Automatic Detection Is Not Enough
Sometimes automatic legend detection is too blunt. You may want different legend text, or you may want to exclude helper artists from the legend entirely. In that case, capture the handles yourself and pass them explicitly.
This is especially useful when the chart contains guide lines, filled areas, or annotations that should not become legend entries.
Use Axes Legends And Figure Legends Intentionally
In multi-plot figures, prefer ax.legend() for subplot-specific legends instead of a global plt.legend().
If one legend should describe the whole figure, build it at the figure level instead:
That avoids duplicating the same legend in every subplot.
Common Pitfalls
- Calling
legend()without assigning useful labels first. - Letting the legend cover important data when a better location is available.
- Using
plt.legend()in complex multi-axes figures whereax.legend()orfig.legend()is clearer. - Automatically including every helper artist instead of curating the legend entries.
- Forgetting layout adjustments when the legend is placed outside the axes.
Summary
- Add a basic legend by labeling artists and calling
legend(). - Use
loc, titles, andbbox_to_anchorto improve readability. - Pass handles explicitly when you need precise control over which entries appear.
- In subplot layouts, choose between
ax.legend()andfig.legend()deliberately.

