Matplotlib Legend: plt.legend() Complete Guide with Examples

Matplotlib Legend: plt.legend() Complete Guide with Examples

Every multi-line plot needs a legend. Without one, viewers have no way to know which line represents which dataset - and a chart that cannot be read is a chart that cannot communicate. Matplotlib's legend() function is the tool for this, and it is far more capable than most tutorials show.

This guide covers everything about the matplotlib legend: how to add one, all 11 location options with numeric codes, how bbox_to_anchor works for precise positioning including placing the legend outside the plot, how to customise the title, font, frame, and columns, how to add legends to bar charts and scatter plots, how to create multiple legends on the same axes, and how to remove a legend entirely. Board Infinity's guide on building a data science portfolio shows how clean, well-labelled visualisations - including properly positioned legends - are a core part of presenting data science work professionally.

Who This Guide Is For

What is a Matplotlib Legend?

A matplotlib legend is a box placed on a plot that maps each plotted element (line, bar, scatter point, patch) to a descriptive label. It tells viewers which colour or marker style corresponds to which data series - making multi-series plots readable and interpretable.

In Matplotlib, legends are added using plt.legend() (in the pyplot interface) or ax.legend() (in the object-oriented interface). Both work identically - the difference is only which interface you are using to build your plot.

How to Add a Matplotlib Legend

There are three ways to add labels that appear in the legend. Understanding all three prevents the most common legend pitfall - calling plt.legend() and seeing an empty box.

If plt.legend() shows an empty box with no entries, it means none of your plot elements have a label= parameter set. Always add label='...' to each plt.plot(), plt.bar(), plt.scatter(), or plt.fill_between() call before calling plt.legend(). Labels starting with an underscore (e.g., label='_nolegend_') are deliberately excluded from the legend.

plt.legend() Syntax and Parameters

Matplotlib Legend Location: All 11 Positions

The loc parameter controls where the legend is placed within the axes. Matplotlib provides 11 named positions and their numeric equivalents.

loc='best' (code 0) is the smartest default - Matplotlib evaluates all 11 positions and picks the one with minimum overlap with plotted data. Use it unless you have a specific reason to pin the legend to a corner. The only downside is that 'best' can be slightly slower on plots with many data points because it must evaluate all positions.

bbox_to_anchor - Matplotlib Legend Position Outside the Plot

bbox_to_anchor overrides loc to give you precise, pixel-perfect control over where the legend appears. It is the only way to move the legend outside the plot area - a common requirement in data visualisation.

bbox_to_anchor accepts a tuple of 2 or 4 values in axes coordinates (0,0 = bottom-left of axes, 1,1 = top-right of axes):

When you move the legend outside the axes using bbox_to_anchor, the legend is technically outside the figure's default bounding box. If you save with plt.savefig('file.png'), the legend will be cut off. Always save with plt.savefig('file.png', bbox_inches='tight') to automatically expand the figure boundary to include the full legend.

Customising the Matplotlib Legend

Legend Title

Font Size and Style

Frame and Background

Legend Columns

Pyplot Legend for Different Chart Types

Legend for Bar Chart

Legend for Scatter Plot

Multiple Legends on the Same Plot

Matplotlib only renders one automatic legend per axes. To show multiple legends, call ax.add_artist() to keep the first legend while adding a second.

When you call ax.legend() a second time, Matplotlib replaces the first legend. To keep both, call ax.add_artist(legend1) after creating the first legend and before creating the second. This keeps legend1 as a permanent artist on the axes while allowing legend2 to become the new active legend. You can repeat this pattern for three or more legends.

Figure-Level Legend with plt.figlegend()

For plots with multiple subplots sharing the same series, a single figure-level legend is cleaner than a legend on every subplot

How to Remove or Hide a Matplotlib Legend

Any label starting with an underscore is excluded from the legend. label='_nolegend_' is the conventional label to explicitly hide a series. This is useful for helper lines (like reference lines, threshold markers, or confidence interval fill areas) that you want plotted but not explained in the legend, since they are either self-evident or described in the caption.

Conclusion

The matplotlib legend is one of those elements where a little extra configuration goes a long way. plt.legend() with no arguments works for simple cases. But real-world visualisation almost always requires at least one customisation - moving the legend outside the plot, adding a title, reducing font size, or spreading entries across multiple columns.

Three things to take away: first, always add label= to your plot calls before plt.legend() - an empty legend box means labels are missing. Second, bbox_to_anchor is the most powerful positioning tool, and you always need bbox_inches='tight' when saving a figure with an outside legend. Third, ax.add_artist(legend1) is the pattern for multiple legends - without it, the second ax.legend() call silently replaces the first.

For data science practitioners, polished visualisations with well-positioned legends are a key part of communicating results in notebooks, dashboards, and reports. Board Infinity's guide on data visualisation with Python covers the broader toolkit - Matplotlib, Seaborn, and Plotly - to help you choose the right tool for every visualisation task.


Frequently Asked Questions

Q1. How do I add a legend in Matplotlib?
Use plt.legend() after your plot calls. Each plotted element must have a label= parameter: plt.plot(x, y, label='My Series'). Calling plt.legend() then reads all labels and displays them in a box on the plot.

Q2. How do I change the matplotlib legend location?
Use the loc parameter: plt.legend(loc='upper right'). There are 11 named positions (best, upper right, upper left, lower left, lower right, right, center left, center right, lower center, upper center, center) or their numeric equivalents (0-10).

Q3. How do I move the legend outside the plot in Matplotlib?
Use bbox_to_anchor: plt.legend(loc='upper left', bbox_to_anchor=(1, 1)). This places the legend to the right of the plot. Always save with plt.savefig('file.png', bbox_inches='tight') to prevent the legend from being cut off.

Q4. How do I add a title to a matplotlib legend?
Use the title= parameter: plt.legend(title='My Legend Title'). Control the title font size with title_fontsize=12. For more styling, access the title directly: ax.legend().get_title().set_fontweight('bold').

Q5. How do I remove a legend in Matplotlib?
Three ways: do not call legend() at all; call ax.get_legend().remove() to delete it after creation; or call ax.get_legend().set_visible(False) to hide it while keeping it in memory.

Q6. How do I add multiple legends to one plot?
Create the first legend and immediately call ax.add_artist(legend1). Then create the second legend normally with ax.legend(...). Without add_artist(), the second call replaces the first.

Q7. How do I put a legend below the plot?
Use bbox_to_anchor=(0.5, -0.1) with loc='upper center' and ncols set to spread entries horizontally: ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.1), ncols=3). Adjust the y value (-0.1, -0.15, etc.) based on how far below you want it.

Mark Lesson Complete (Matplotlib Legend: plt.legend() Complete Guide with Examples)