Adding a legend

To match data series on plots with their labels, such as by their line styles and marker styles, we add the following:

plt.legend()

The label of each data series can be specified within each plt.plot() command with the label parameter.

By default, Matplotlib chooses the best location to minimize overlap with data points and add transparency to the legend face color in case of overlapping. However, this does not always guarantee the location to be ideal in each case. To adjust the location, we can't pass loc settings , such as by using plt.legend(loc='upper left').

Possible loc settings are as follows:

  • 'best': 0 (only implemented for axes' legends)
  • 'upper right': 1
  • 'upper left': 2
  • 'lower left': 3
  • 'lower right': 4
  • 'right': 5 (the same as 'center right'; for back-compatibility)
  • 'center left': 6
  • 'center right': 7
  • 'lower center': 8
  • 'upper center': 9
  • 'center': 10

You can also set loc as normalized coordinates with respect to the parent, which is usually the axes' area; that is, edges of axes are at 0 and 1. For instance, plt.legend(loc=(0.5,0.5)) sets the legend right in the middle.

Let's try to set the legend to our multiline plot in the lower-right corner with absolute coordinates, plt.legend(loc=(0.64,0.1)), as shown in the following created plot:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.48.143