Change the legend position in Matplotlib

Python

Matplotlib

Legend

Change position

Luc B.

Python

Matplotlib

Although Matplotlib tries to automatically place legends in non-disruptive places, it occasionaly covers up important sections of data. Fortunately, Matplotlib provides a simple API for manually placing legends, and it even supports placing legends outside the plot area altogether.

Code Example

Use the loc argument to plt.legend() to change the legend position. loc can be a string or a pair of coordinates.

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')

# Adjust the legend position here
plt.legend(loc='upper right')

plt.show()

png

Valid loc strings are:

'best'
'upper right'
'upper left'
'lower left'
'lower right'
'right'
'center left'
'center right'
'lower center'
'upper center'
'center'

More Examples

Use Coordinates

The legend can also be positioned using x-y coodinates. These are relative to the coordinate system of your plot.

Note that if your chosen coordinates place the legend outside the plot area, the legend may be beyond the figure dimensions and thus won't be visible. However, Matplotlib provides the plt.tight_layout() method, which forces Matplotlib to recompute the figure dimensions so all text elements fit in the figure.

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

# Pass coordinates instead of a string
plt.legend(loc=[1.1, 0.5])

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

plt.show()

png