Create a legend in Matplotlib

Python

Matplotlib

Legend

Create

Luc B.

Python

Matplotlib

Legends are useful for creating plots that compare multiple data sets. When used properly, they provide important information that makes plots much easier to interpret.

Code Example

Use the plt.legend() function to create a legend in Matplotlib.

import matplotlib.pyplot as plt
import numpy as np

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

# Create the legend here
plt.legend()

plt.show()

png

In this method, the legend labels are passed to plt.plot(), and plt.legend() picks them up. While this is a convient way to use plt.legend(), there are other ways to accomplish the same thing.

More Examples

Pass Labels to plt.legend()

Alternatively, pass legend labels directly to plt.legend() as a list or tuple of strings. The labels are assigned to plot elements based on the order the plot elements were created.

plt.plot(x, x**2)
plt.plot(x, 1-x)

# Pass labels here
plt.legend(('Parabola', 'Line'))

plt.show()

png

Pass Plot Elements and Labels to plt.legend()

For the most control, pass references to the plot elements and the corresponding legend labels to plt.legend().

parabola, = plt.plot(x, x**2)
line, = plt.plot(x, 1-x)

# Pass elements and labels here
plt.legend((parabola, line), ('Parabola', 'Line'))

plt.show()

png