Adding a matplotlib legend
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
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.
Related reading
- Adding a y-axis label to secondary y-axis in matplotlib
- Adding custom jars to pyspark in jupyter notebook
- Adding Dropping Column instance into a Pipeline
- Adding meta-information/metadata to pandas DataFrame
- Adding a method to an existing object instance in Python
- Adding a method to an existing object instance in Python
- adding noise to a signal in python
- Adding Tensorboard summaries from graph ops generated inside Dataset map function calls
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.