Matplotlib - Legends



In general, a legend in a graph provides a visual representation of the data depicted along the Y-axis, often referred to as the graph series. It is a box containing a symbol and a label for each series in the graph. A series could be a line in a line chart, a bar in a bar chart, and so on. The legend is helpful when you have multiple data series on the same plot, and you want to distinguish between them. In the following image, we can observe the legend in a plot (highlighted with a red color rectangle) −

Intro Image

Adding legend to a matplotlib plot

To add a legend to a Matplotlib plot, you typically use the matplotlib.pyplot.legend() function. This function is used to add a legend to the Axes, providing a visual guide for the elements in the plot.

Syntax

Following is the syntax of the function

matplotlib.pyplot.legend(*args, **kwargs)

The function can be called in different ways, depending on how you want to customize the legend.

Matplotlib automatically determines the elements to be added to the legend while call legend() without passing any extra arguments,. The labels for these elements are taken from the artists in the plot. You can specify these labels either at the time of creating the artist or by using the set_label() method.

Example 1

In this example, the legend takes the data from the label argument is used when creating the plot.

import matplotlib.pyplot as plt

# Example data
x = [1, 2, 3]
y = [2, 4, 6]

# Plotting the data with labels
line, = plt.plot(x, y, label='Legend describing a single line')

# Adding a legend
plt.legend()

# Show the plot
plt.show()
print('Successfully Placed a legend on the Axes...')

Output

Output Image
Successfully Placed a legend on the Axes...

Example 2

Here is the alternative way of using the set_label() method on the artist.

import matplotlib.pyplot as plt

# Example data
x = [1, 2, 3]
y = [2, 4, 6]

# Plotting the data with labels
line, = plt.plot(x, y)
line.set_label('Place a legend via method')

# Adding a legend
plt.legend()

# Show the plot
plt.show()
print('Successfully Placed a legend on the Axes...')

Output

Output Image2
Successfully Placed a legend on the Axes...

Manually adding the legend

You can pass an iterable of legend artists followed by an iterable of legend labels to explicitly control which artists have a legend entry.

Example 1

Here is an example of calling the legend() function by listing artists and labels.

import matplotlib.pyplot as plt

# Example data
x = [1, 2, 3]
y1 = [2, 4, 6]
y2 = [1, 3, 5]
y3 = [3, 6, 9]

# Plotting the data
line1, = plt.plot(x, y1)
line2, = plt.plot(x, y2)
line3, = plt.plot(x, y3)

# calling legend with explicitly listed artists and labels
plt.legend([line1, line2, line3], ['Label 1', 'Label 2', 'Label 3'])

# Show the plot
plt.show()
print('Successfully Placed a legend on the Axes...')

Output

Output Image3
Successfully Placed a legend on the Axes...

Example 2

Here is an example of calling the legend() function only by listing the artists. This approach is similar to the previous one but in this case, the labels are taken from the artists' label properties.

import matplotlib.pyplot as plt

# Example data
x = [1, 2, 3]
y1 = [2, 4, 6]
y2 = [1, 3, 5]

# Plotting the data with labels
line1, = plt.plot(x, y1, label='Label 1')
line2, = plt.plot(x, y2, label='Label 2')

# Adding a legend with explicitly listed artists
plt.legend(handles=[line1, line2])

# Show the plot
plt.show()
print('Successfully Placed a legend on the Axes...')

Output

Output Image4
Successfully Placed a legend on the Axes...

Example 3

In this example, we first plot two sets of data, and then we add a legend by calling the legend() function with a list of strings representing the legend items.

import matplotlib.pyplot as plt

# Example data
x = [1, 2, 3, 4, 5, 6]
y1 = [1, 4, 2, 6, 8, 5]
y2 = [1, 5, 3, 7, 9, 6]

# Plotting the data
plt.plot(x, y1)
plt.plot(x, y2)

# Adding a legend for existing plot elements
plt.legend(['First line', 'Second line'], loc='center')

# Show the plot
plt.show()
print('Successfully Placed a legend on the Axes...')

Output

Output Image5
Successfully Placed a legend on the Axes...

Adding legend in subplots

To add the legends in each subplot, we can use the legend() function on each axes object of the figure.

Example 1

Here is an example that adds the legend to the each subplot of a matplotlib figure. This approach uses the legend() function on the axes object.

import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7, 3.50]
plt.rcParams["figure.autolayout"] = True

# Sample data
x = np.linspace(-2, 2, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)

# Create the figure with subplots
f, axes = plt.subplots(3)

# plot the data on each subplot and add lagend
axes[0].plot(x, y1, c='r', label="sine")
axes[0].legend(loc='upper left')
axes[1].plot(x, y2, c='g', label="cosine")
axes[1].legend(loc='upper left')
axes[2].plot(x, y3, c='b', label="tan")
axes[2].legend(loc='upper left')

# Display the figure
plt.show()

Output

On executing the above code we will get the following output −

Output Image 6

Adding multiple legends in one axes

To draw multiple legends on the same axes in Matplotlib, we can use the axes.add_artist() method along with the legend() function.

Example 2

The following example demonstrates how to add multiple legends in one axes of the matplotlib figure.

from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7, 4]
plt.rcParams["figure.autolayout"] = True

# plot some data 
line1, = plt.plot([1, 2, 3], label="Line 1", linestyle='--')
line2, = plt.plot([3, 2, 1], label="Line 2", linewidth=4)

# Add first legend at upper right of the axes
first_legend = plt.legend(handles=[line1], loc='upper right')

# Get the current axes to add legend
plt.gca().add_artist(first_legend)

# Add second legend at lower right of the axes
plt.legend(handles=[line2], loc='lower right')

# Display the output
plt.show()

Output

On executing the above code we will get the following output −

Output Image 7
Advertisements