TechBuzzPro

Matplotlib Legend Outside Plot: Step-by-Step

· 4 min read · Apps & Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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 pyplot interface.

Step-by-Step

  1. 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.
  2. Call the legend() method with bbox_to_anchor.
    The key is to pass a tuple to bbox_to_anchor that 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 with loc='upper left', the legend's upper-left corner is anchored at that point.
  3. Adjust the loc parameter to control which part of the legend is anchored.
    If you use loc='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, use loc='upper center' with bbox_to_anchor=(0.5, -0.05).
  4. Call plt.tight_layout() or fig.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.
  5. 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.
  6. For legends below the plot, use bbox_to_anchor=(0.5, -0.1) with loc='upper center'.
    This places the legend below the x-axis. You may need to adjust the bottom margin with subplots_adjust(bottom=0.2) to avoid clipping.
  7. Save the figure with bbox_inches='tight' if needed.
    When saving, use plt.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 loc and bbox_to_anchor incorrectly. The loc specifies which part of the legend is anchored to the point given by bbox_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_anchor value 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 of ax.legend(). This creates a single legend for the whole figure, and you can place it outside using similar parameters.
  • Experiment with borderaxespad to fine-tune spacing. This parameter controls the padding between the axes and the legend.
  • If the legend is too large, consider using ncol to put entries in multiple columns. This can make the legend more compact.

Troubleshooting

  • Legend is cut off when saving. Add bbox_inches='tight' to savefig(), or manually increase the figure size with fig.set_size_inches().
  • Legend overlaps the plot. Increase the x value in bbox_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 passing bbox_to_anchor to the legend() call and that you haven't overridden it later.
  • The legend is too far from the plot. Decrease the x value (e.g., to 1.01) or adjust borderaxespad to 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.