Adding a Legend to the Plot
In this lesson, we will learn how to add a legend to the plot.
We'll cover the following...
What is a legend
?
A legend
provides a description for an element in the figure. A legend helps the user understand a figure when the figure contains many elements. For example, if there are two curves on a graph, then the legend can help the user distinguish between the curves.
There is more than one way to add a legend
to a figure. In this lesson, we will learn two methods. Both use the plot()
function. The difference, however, is in how the two methods set their labels.
Adding a legend
without labels
In this method, we don’t pass the labels to the legend()
, because the labels are passed in plot()
. When legend()
is called, the Axes would detect the labels automatically.
Press + to interact
import numpy as npimport matplotlib.pyplot as pltpoints = np.linspace(-5, 5, 256)y1 = np.tanh(points) + 0.5y2 = np.sin(points) - 0.2fig, axe = plt.subplots(dpi=800)axe.plot(points, y1, label="tanh")axe.plot(points, y2, label="sin")axe.legend()fig.savefig("output/output.png")plt.close(fig)
As we can see in the example ...