To create legned in matplotlib plot the matplotlib.pyplot.legend() function is required. The general form of matplotlib.pyplot.legend function can be written as:
Example 1 - Create plot containing following functions \begin{eqnarray} y1 &=& \sin(x)\\ y2 &=& \cos(x)\\ y3 &=& 0.5\cdot x + 1\\ y4 &=& 0.25\cdot x + 1 \end{eqnarray} and show the legend using the plt. legend() command.
Solution - The solution consist of three steps i.e. import libraries, calculate data, and plot the functions. For this example, we will need two libraries numpy and matplotlib.
Figure 1 - Matplotlib plot showing four different mathematical functions with legend position at top left corner.
Example 2 Create a plot with legned that contains the same functions from Example 1 using matplotlib.pyplot.subplots() function ?
Soltions - Look into previous example to see how the functions were generated. To code for generating x-values and y1,y2,y3, and y4 values is given below.
Figure 2 - Plot from Example 1 created using matplotlib.pyplot.subplots()
Example 3 Plot functions 0.5*sin(x) and sin(x) in range from 0 to 5 by explicitly listing the legend and using matplotlib.pyplot.subplots() function.
Solution: As in previous examples we have to import two libraries i.e. numpy and matplotlib.
Figure 3 - Plot with legend created by explicitly listing the legend and using matplotlib.pyplot.subplots() function
Instead of creating labels in the plot function, we could symply type these labels inside the legend function. However, to do this we have to remove the labels from the plot function.
matplotlib.pyplot.legend(*args, **kwargs)In the legend function, if specified without any extra arguments, the arguments are automatically determined. However, labels should be defined. The labels of multiple curves can be defined in two ways:
- defining the label inside the matplotlib.pyplot.plot function as
plt.plot(x,y, label="label name")
or
- using set_label() method
ax.set_label("label name")
. It should be noted that in the second case the plot was created using fig,ax = plt.subplots(). Using plt.figure() with set_label() function will raise result in AttributeError: module 'matplotlib.pyplot' has no attribute 'set_label'
ax.legend([plo1, plot2, plot3], ['label1', 'label2', label3'])
Example 1 - Create plot containing following functions \begin{eqnarray} y1 &=& \sin(x)\\ y2 &=& \cos(x)\\ y3 &=& 0.5\cdot x + 1\\ y4 &=& 0.25\cdot x + 1 \end{eqnarray} and show the legend using the plt. legend() command.
Solution - The solution consist of three steps i.e. import libraries, calculate data, and plot the functions. For this example, we will need two libraries numpy and matplotlib.
import numpy as npThe second step is to generate the data. The x values will be created using the np.arange command in a range from 0 to 5 with a step size of 0.001.
import matplotlib.pyplot as plt
x = np.arange(0,5,0.001)The functions will be created also using numpy functions sine and cosine while the remaining two functions require basic mathematical operations (multiplication and addition).
y1 = np.sin(x)To plot this function first we need to set the figure size. As before we will use \(12\times 8[\mathrm{in}]\) figure size and matplotlib.pyplot.plot method to plot previously calculated function. To set the grid in the plot we will use matplotlib.pyplot.grid() function.
y2 = np.cos(x)
y3 = 0.25*x+1
y4 = 0.5*x + 1
plt.figure(figsize=(12,8))To set the legend in the plot we will use the matploltib.pyplot.legend() function.
plt.plot(x,y1, label = "sin(x)")
plt.plot(x,y2,label="cos(x)")
plt.plot(x,y3, label="0.5*x + 1"
plt.plot(x,y4, label="0.25*x + 1")
plt.grid(True)
plt.legend()As seen from the previous code line the legend function does not require any argument since all labels are defined inside each of the plot functions. To show the plot we will use the matplotlib.pyplot.show function.
plt.show()The entire code used in this example as well as the output are given below. The output (result) is shown in Figure 1.
Soltions - Look into previous example to see how the functions were generated. To code for generating x-values and y1,y2,y3, and y4 values is given below.
x = np.arange(0,5,0.001)The function matplotlib.pyplot.subplots() return two objects and these are fig (figure) and ax (axes) so we will define two variables (fig, ax) that will be equal to the aforementioned function. We will set the figure size (figisize) to \(12\times 8 [\mathrm{in}]\) as an argument of a matplotlib.pyplot.subplots() function.
y1 = np.sin(x)
y2 = np.cos(x)
y3 = 0.5*x + 1
y4 = 0.25*x + 1
fig, ax = plt.subplots(figsize=(12,8))Now we will use the ax object to plot each function and each plot is assigned to a specific variable name (curve1, ... curve4). After plots are prepared, the grid is defined, and labels are assigned to each plot (variable from curve1 to cruve4). To show all the previously defined labels we have to call a matplotlib.pyplot.legend() function. Finally, to show the plot we used the matplotlib.pyplot.show().
curve1, = ax.plot(x,y1)Output:
curve2, = ax.plot(x,y2)
curve3, = ax.plot(x,y3)
curve4, = ax.plot(x,y4)
ax.grid(True)
curve1.set_label('sin(x)')
curve2.set_label('cos(x)')
curve3.set_label('0.5*x+1')
curve4.set_label('0.25*x+1')
ax.legend()
plt.show()
Solution: As in previous examples we have to import two libraries i.e. numpy and matplotlib.
import numpyTo generate the x and y coordinates of the function first we have to generate the x values in a range from 0 to 5 and then use these values as arguments to calculate y. The x values will be created from 0 to 5 using 0.001 steps using function np.arange. Both functions 0.5*sin(x) and sin(x) will be calculated for all values of x using np.sin(x) function.
import matplotlib.pyplot as plt
x = np.arange(0,5,0.001)Regarding the legend function and how to set labels the procedure is very simple. Instead of using set_label function, we will write labels inside the plot functions.
y1 = 0.5*np.sin(x)
y2 = np.sin(x)
import matplotlib.pyplot
import numpy as np, import matplotlib pypplot as plt, import random
fig, ax = plt.subplots(figsize=(12,8))
line1, = ax.plot(x,y1, label="0.5*sin(x)")
line2, = ax.plot(x,y2, label="sin(x)")
ax.legend(handles=[line1,line2])
ax.grid(True)
plt.show()
line1, = ax.plot(x,y1)
line2, = ax.plot(x,y2)
ax.legend(['0.5*sin(x)', 'sin(x)'])