Place a legend outside the plot area in Matplotlib

Python

Matplotlib

Legend

Place outside plot

Luc B.

Python

Matplotlib

Often there's no good place for a legend in your Matplotlib visualization, and you need to move the legend outside the plot area. Matplotlib makes this easy by allowing users to specify coordinates for the legend.

Code Example

Pass x-y coordinates as the loc argument to plt.legend() to place a legend outside the plot area. These coordinates are relative to the coordinate system of your plot, so as long as they are beyond the plot's x and y limits, the legend will be outside the plot area.

Note that if a legend is placed outside the plot area, it can exceed the figure dimensions and be partially or completely hidden. To resolve this, use the plt.tight_layout() method, which forces Matplotlib to recompute the figure dimensions so all text elements fit in the figure.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1)
plt.plot(x, x**2, label='Line 1')
plt.plot(x, 1-x, label='Line 2')

# Place the legend outside the plot area
plt.legend(loc=[1.1, 0.5])

# Recompute the figure dimensions so the legend isn't hidden
plt.tight_layout()

plt.show()

png