Tutorial by Examples

Suppose you have multiple lines in the same plot, each of a different color, and you wish to make a legend to tell what each line represents. You can do this by passing on a label to each of the lines when you call plot(), e.g., the following line will be labelled "My Line 1". ax.plot(...
Sometimes it is necessary or desirable to place the legend outside the plot. The following code shows how to do it. import matplotlib.pylab as plt fig, ax = plt.subplots(1, 1, figsize=(10,6)) # make the figure with the size 10 x 6 inches fig.suptitle('Example of a Legend Being Placed Outside of...
Sometimes you will have a grid of subplots, and you want to have a single legend that describes all the lines for each of the subplots as in the following image. In order to do this, you will need to create a global legend for the figure instead of creating a legend at the axes level (which wil...
If you call plt.legend() or ax.legend() more than once, the first legend is removed and a new one is drawn. According the official documentation: This has been done so that it is possible to call legend() repeatedly to update the legend to the latest handles on the Axes Fear not, though: It ...

Page 1 of 1