Confused about pyplot and matplotlib? See Matplotlib, Pyplot, Pylab etc: What's the difference between these and when to use each?
All examples assume you're working on the pyplot interface.
Call plt.legend() with a list of legends as arguments.
This is the simplest possible use case.
While you can just pass a list with multiple texts to plt.legend(), it's better to label each plot individually so there are no errors.
1) Add a label parameter to each plot.
If there are multiple axes on your plot, you can add legends to a single axis if you wish.
If you don't provide a location for the legend, matplotlib tries to figure out by itself where it should place it.
To force another location, set parameter loc using location a string (e.g. 'upper left' or 'lower right') as argument.
value, matplotlib tries to figure out where to place it).
Some libraries such as Pandas default to setting legends in plots.
If you have many lines or plots in the same axes, it can get a litle bit difficult to view them all.
Use argument bbox_to_anchor to reposition the legend box.
Sometimes the order in which legend labels are displayed is not the most adequate.
For example, in the first graph, the order the labels are shown does not match the order the lines are plotted, so it can make visualization a bit harder, especially when there are many groups of data in the same axes.
1) get current labels via get_legend_handles_labels() after plotting.
2) sort the handles (images) and labels the way you want.
3) call plt.legend() passing the modified handles and labels.
to know which line is which.