Matplotlib plt.legend is the go-to function for adding clear, informative legends to your Python plots. Used correctly, it helps viewers instantly identify which lines, markers, or colors correspond to specific data series.
By controlling labels, placement, and styling, plt.legend turns dense visualizations into audience-friendly stories. The following sections walk through common patterns, configuration options, and practical workflows that leverage the power of legends in Matplotlib.
| Parameter | Default | Description | Typical Use |
|---|---|---|---|
| labels | None | List of label texts for each artist. | Manual override when automatic detection is insufficient. |
| loc | 'best' | Location code or string for legend box placement. | Avoid overlapping key data regions. |
| ncol | 1 | Number of columns in the legend layout. | Compact horizontal arrangement for many entries. |
| frameon | True | Whether to draw a border around the legend. | Toggle for minimal or framed styles. |
| fontsize | Text size for legend entries. | Adjust readability for slides or publications. |
Basic Usage of plt.legend
Calling plt.legend without arguments automatically picks up labels from plot commands that include a label parameter.
For explicit control, pass a list of strings in the same order as the plotted artists. This approach is helpful when you need to normalize labeling across multiple subplots or layered commands.
Labeling and Handles
Using Handles and Labels Directly
plt.legend accepts handles and labels separately, which is useful when you want to reorder, filter, or combine artists from different axes. By supplying custom handles and labels, you gain fine-grained control over what appears in the legend and in which sequence.
Label Prop in Plot Commands
Set the label argument in plot, scatter, or bar calls, then invoke plt.legend to collect them automatically. This style keeps labeling close to data generation and reduces the chance of mismatched entries.
Positioning and Layout Control
Location Strategies
The loc parameter supports string codes like 'upper right', 'center left', and integer codes following the Matplotlib location schema. Choosing an appropriate location reduces occlusion of high-value regions and improves visual clarity.
Columns and Spacing
Use ncol to split entries into multiple columns, which saves vertical space and works well for dashboards or slides. Fine-tune border padding, column spacing, and font size to align the legend with your overall design language.
Styling and Aesthetics
Frame, Transparency, and Colors
Toggle frameon to show or hide the legend border, and adjust edgecolor, facecolor, and framealpha for stronger contrast or subtle integration. These options help the legend adapt to complex backgrounds or thematic color schemes.
Font and Marker Scaling
Control fontsize, labelspacing, and borderpad to balance compactness and readability. When markers dominate the legend, consider legend handlelength and handletextpad to keep markers informative without overcrowding the text.
Advanced Customization and Best Practices
- Match label order to the narrative you want viewers to follow.
- Test legibility on projected screens and printed pages, adjusting contrast accordingly.
- Use consistent naming across subplots to simplify comparison.
- Leverage bbox_to_anchor and loc together for precise placement.
- Consider transparent backgrounds for overlays on imagery or dense plots.
- Document custom legend logic in your code to ease future maintenance.
FAQ
Reader questions
How do I place the legend outside the plotting area?
Use bbox_to_anchor with loc to position the legend outside axes, for example plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)). Combine this with adjusted subplot parameters to ensure the legend remains fully visible.
Can I create multiple legends on the same axes?
Yes, add the first legend to an axes object, then create a second legend and call set_zorder to layer them, or use legend.remove to replace it selectively. Managing zorder and axes patches helps avoid visual conflicts.
What happens if I omit labels in my plot commands?
plt.legend falls back to automatic labels, which often produce empty entries labeled '_nolegend_' if no label was set. Explicitly passing labels to plot or supplying them directly to legend prevents confusing placeholders.
How can I keep the legend readable with many entries?
Switch to multiple columns via ncol, reduce font size, or group related series into a single annotated entry. Strategic filtering using custom handles and labels can also declutter dense visualizations.