Change the vertical spacing between legend entries in Matplotlib

Python

Matplotlib

Legend

Change vertical spacing

Luc B.

Python

Matplotlib

Legend

Plots with confusing, difficult-to-read legends are, by extension, confusing and difficult to read. Sometimes simply adding vertical space between legend entries can vastly improve a plot's readability.

Code Example

Use the labelspacing argument to plt.legend() to change the vertical space between labels.

import matplotlib.pyplot as plt

plt.plot([0, 1], [0, 1.0], label='Label 1')
plt.plot([0, 1], [0, 1.1], label='Label 2')
plt.plot([0, 1], [0, 1.2], label='Label 3')

# Change the label spacing here
plt.legend(labelspacing=2)

plt.show()

png

The spacing is specified in font-size units.

More Examples

Object-Oriented Interface

The same functionality is just as easily accomplished with Matplotlib's object-oriented interface.

ax = plt.axes()

ax.plot([0, 1], [0, 1.0], label='Label 1')
ax.plot([0, 1], [0, 1.1], label='Label 2')
ax.plot([0, 1], [0, 1.2], label='Label 3')

# Change the label spacing here
ax.legend(labelspacing=2)

plt.show()

png