Legends and annotations
Legends are an important element that is used to identify the plot
elements in a figure. The easiest way to show a legend inside a figure is to use the label
argument of the plot
function, and show the labels by calling the plt.legend()
method:
>>> x = np.linspace(0, 1, 20) >>> y1 = np.sin(x) >>> y2 = np.cos(x) >>> y3 = np.tan(x) >>> plt.plot(x, y1, 'c', label='y=sin(x)') >>> plt.plot(x, y2, 'y', label='y=cos(x)') >>> plt.plot(x, y3, 'r', label='y=tan(x)') >>> plt.lengend(loc='upper left') >>> plt.show()
The output for the preceding command as follows:
The loc
argument in the legend command is used to figure out the position of the label box. There are several valid location options: lower left
, right
, upper left
, lower center
, upper right
, center
, lower right
, upper right
, center right
, best
, upper center
, and center left
. The default position setting is upper right
. However, when we...