Use multiple columns in a Matplotlib legend

Python

Matplotlib

Legend

Use multiple columns

Luc B.

Python

Matplotlib

Legend

As legends get long, they can take up a lot of vertical space and cover up your visualization. By organizing legend labels into multiple columns, it's easier to non-disruptively place the legend.

Code Example

Use the ncol argument to plt.legend() to specify the number of columns the legend should have.

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')
plt.plot([0, 1], [0, 1.3], label='Label 4')
plt.plot([0, 1], [0, 1.4], label='Label 5')

# Change the number of columns here
plt.legend(ncol=2)

plt.show()

png