Matplotlib Legend Outside Plot: Step-by-Step
In this article
Placing a Matplotlib legend outside the plot area is a common need when the legend overlaps data or when you want to keep the plotting area clean and uncluttered. By default, Matplotlib places the legend inside the axes, but you can easily move it outside using the bbox_to_anchor parameter and the loc parameter of the legend() function. This guide walks you through the exact steps, including how to adjust the layout so nothing gets cut off, and covers common pitfalls and troubleshooting tips.
What You'll Need
- Python installed (3.6 or later recommended).
- Matplotlib installed. If not, install it with
pip install matplotlib. - A basic understanding of Python and Matplotlib's
pyplotinterface.
Step-by-Step
- Import Matplotlib and create a simple plot.
Start with a minimal example to see the default legend placement. For instance, plot two lines with labels. - Call the
legend()method withbbox_to_anchor.
The key is to pass a tuple tobbox_to_anchorthat specifies the legend's position relative to the axes. For example,bbox_to_anchor=(1.05, 1)places the legend just outside the right edge, aligned with the top of the axes. Combined withloc='upper left', the legend's upper-left corner is anchored at that point. - Adjust the
locparameter to control which part of the legend is anchored.
If you useloc='upper left', the legend's top-left corner is placed at the anchor point. For a legend to the right of the plot,loc='upper left'is typical. For a legend below the plot, useloc='upper center'withbbox_to_anchor=(0.5, -0.05). - Call
plt.tight_layout()orfig.tight_layout().
This adjusts subplot parameters so that the legend (and other elements) fit within the figure canvas. Without this, the legend may be clipped or the plot area may shrink unexpectedly. - Alternatively, use
fig.subplots_adjust()to manually reserve space.
If you need more control, you can adjust the right margin (e.g.,fig.subplots_adjust(right=0.8)) to leave room for the legend on the right side. - For legends below the plot, use
bbox_to_anchor=(0.5, -0.1)withloc='upper center'.
This places the legend below the x-axis. You may need to adjust thebottommargin withsubplots_adjust(bottom=0.2)to avoid clipping. - Save the figure with
bbox_inches='tight'if needed.
When saving, useplt.savefig('plot.png', bbox_inches='tight')to ensure the legend is included in the saved file without being cut off.
Common Mistakes
- Forgetting to call
tight_layout()or adjust margins. The legend may appear outside the figure's visible area, especially when saving. - Using
locandbbox_to_anchorincorrectly. Thelocspecifies which part of the legend is anchored to the point given bybbox_to_anchor. Mixing them up can place the legend in unexpected spots. - Not providing labels to the plot elements. If you don't set labels in
plot(), the legend will be empty or show generic entries. - Using a negative
bbox_to_anchorvalue without adjusting margins. A negative x or y coordinate places the legend outside the axes, but the figure may not automatically accommodate it.
Tips
- Use
loc='center left'for a legend on the right side. This keeps the legend vertically centered relative to the anchor point, which often looks better. - For multiple subplots, use
fig.legend()instead ofax.legend(). This creates a single legend for the whole figure, and you can place it outside using similar parameters. - Experiment with
borderaxespadto fine-tune spacing. This parameter controls the padding between the axes and the legend. - If the legend is too large, consider using
ncolto put entries in multiple columns. This can make the legend more compact.
Troubleshooting
- Legend is cut off when saving. Add
bbox_inches='tight'tosavefig(), or manually increase the figure size withfig.set_size_inches(). - Legend overlaps the plot. Increase the
xvalue inbbox_to_anchor(e.g., from 1.05 to 1.2) to move it further away. - Legend appears inside the plot despite using
bbox_to_anchor. Ensure you are passingbbox_to_anchorto thelegend()call and that you haven't overridden it later. - The legend is too far from the plot. Decrease the
xvalue (e.g., to 1.01) or adjustborderaxespadto a smaller number. - Legend doesn't show at all. Check that you have labels on your plot elements and that you called
legend().
Frequently Asked Questions
How do I place the legend above the plot?
Use bbox_to_anchor=(0.5, 1.05) with loc='lower center'. This places the legend above the axes, centered horizontally.
Can I place the legend outside the plot without using bbox_to_anchor?
Not directly. The bbox_to_anchor parameter is the standard way to position the legend outside the axes. Alternatively, you can use loc with strings like 'upper right' but that still places it inside.
How do I place the legend outside the plot for a subplot?
For a single subplot, use ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left'). For multiple subplots, consider fig.legend() and place it outside the entire figure.
Why does my legend get cut off when I save the figure?
This happens because the default figure size doesn't accommodate the legend. Use bbox_inches='tight' when saving, or increase the figure size and adjust margins.
What does loc do when using bbox_to_anchor?
loc determines which corner of the legend is placed at the anchor point. For example, loc='upper left' means the legend's upper-left corner is at the anchor.
Can I place the legend outside the plot on the left side?
Yes, use bbox_to_anchor=(-0.1, 1) with loc='upper right'. Adjust the negative value to control the distance.