In the previous part of the Matplotlib series we were talking about the title and axis labels. Today let’s see how to add a legend to the graph.
If there are multiple lines on a graph, it’s easy to lose track of them. That’s why a legend comes in handy. It displays each line along with a label. We already created a legend in one of the first parts of the series. Here’s the example again:
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-10, 10, 100)
# Here are the three functions.
y1 = x ** 2 - 2 * x + 3
y2 = 10 * np.sin(x)
y3 = 2 * x + 1
# Let's create the figure and an axis.
fig, ax = plt.subplots()
# Let's plot the three functions. We'll pass the red, green and blue colors to the functions and the labels
# that will later appear in the legend.
ax.plot(x, y1, color='red', label='y1(x)')
ax.plot(x, y2, color='green', label='y2(x)')
ax.plot(x, y3, color='blue', label='y3(x)')
# Let's add the names of the two axes (x and y).
ax.set_xlabel('x')
ax.set_ylabel('y')
# Finally, let's add the legend.
ax.legend()
As you can see, all we have to do is specify the labels in the code. Now, as you might suspect, we can tweak the legend a little using some parameters.
First of all, we can decide where exactly the legend should appear. To this end we can use the loc parameter. Here are the values we use with this parameter, both string and numerical ones:
loc = 0 or loc = ‘best’ loc = 1 or loc = ‘upper right’ loc = 2 or loc = ‘upper left’ loc = 3 or loc = ‘lower left’ loc = 4 or loc = ‘lower right’ loc = 5 or loc = ‘right’ loc = 6 or loc = ‘center left’ loc = 7 or loc = ‘center right’ loc = 8 or loc = ‘lower center’ loc = 9 or loc = ‘upper center’ loc = 10 or loc = ‘center’
Have a look:
fig, ax = plt.subplots()
ax.plot(x, y1, color='red', label='y1(x)')
ax.plot(x, y2, color='green', label='y2(x)')
ax.plot(x, y3, color='blue', label='y3(x)')
# lower left
ax.legend(loc=3)
fig, ax = plt.subplots()
ax.plot(x, y1, color='red', label='y1(x)')
ax.plot(x, y2, color='green', label='y2(x)')
ax.plot(x, y3, color='blue', label='y3(x)')
# center right
ax.legend(loc=7)
The elements in the legend are by default positioned in one column. You can use the ncol parameter to change the number of columns.
fig, ax = plt.subplots()
ax.plot(x, y1, color='red', label='y1(x)')
ax.plot(x, y2, color='green', label='y2(x)')
ax.plot(x, y3, color='blue', label='y3(x)')
# two columns
ax.legend(ncol=2)