How to insert legend in matplotlib

The matplotlib.pyplot method provides a way to plot interactive figures in Python, similar to MATLAB. Given a pyplot instance, the matplotlib.pyplot.legend() method is used to place a legend on the axes.

svg viewer

Call Signatures

There are three call signatures available for the matplotlib.pyplot.legend() method:

1. Using legend():

These are used to automatically detect legend elements. When no arguments are passed to the legend() method, the elements to be added in the legend are automatically detected, and their assigned labels are used in the legend.

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 8, 1000)
y1 = np.sin(x)
y2 = np.arcsin(x)
plt.plot(x, y1, label='sine')
plt.plot(x, y2, label='arcsine')
plt.legend()
plt.show()

2. Using legend(labels):

These are used to label existing elements. This method can be used to create a legend for the elements already existing on the axes. legend(labels) method is called using an iterable of strings, where each string is used as a label for the elements in the order they were created.

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 8, 1000)
y1 = np.sin(x)
plt.plot([4, 7, 9])
plt.plot(x, y1, '-b')
plt.legend(['Line1', 'Sine'])
plt.show()

Note: This way of using the legend is often discouraged since the relationship between the elements and the passed labels exists only through their order and can be easily confused.


3. Using legend(handles, labels):

These are used to explicitly define elements and style. For full control of the legend, you can pass the iterable of elements followed by the iterable of string labels arranged in order.

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 8, 1000)
y1 = [4, 7, 9]
y2 = np.sin(x)
y3 = np.arcsin(x)
line, = plt.plot(y1)
sine, = plt.plot(x, y2)
arcsine, = plt.plot(x, y3)
plt.legend(handles = [line, sine, arcsine],
labels = ['Line', 'Sine', 'Arcsine'])
plt.show()

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved