Note
Go to the end to download the full example code.
Legend guide#
This legend guide extends the legend
docstring -
please read it before proceeding with this guide.
This guide makes use of some common terms, which are documented here for clarity:
- legend entry#
A legend is made up of one or more legend entries. An entry is made up of exactly one key and one label.
- legend key#
The colored/patterned marker to the left of each legend label.
- legend label#
The text which describes the handle represented by the key.
- legend handle#
The original object which is used to generate an appropriate entry in the legend.
Controlling the legend entries#
Calling legend()
with no arguments automatically fetches the legend
handles and their associated labels. This functionality is equivalent to:
The get_legend_handles_labels()
function returns
a list of handles/artists which exist on the Axes which can be used to
generate entries for the resulting legend - it is worth noting however that
not all artists can be added to a legend, at which point a "proxy" will have
to be created (see Creating artists specifically for adding to the legend (aka. Proxy artists) for further details).
Note
Artists with an empty string as label or with a label starting with an underscore, "_", will be ignored.
For full control of what is being added to the legend, it is common to pass
the appropriate handles directly to legend()
:
Renaming legend entries#
When the labels cannot directly be set on the handles, they can be directly passed to
Axes.legend
:
If the handles are not directly accessible, for example when using some
Third-party packages, they can be accessed
via Axes.get_legend_handles_labels
. Here we use a dictionary to rename existing
labels:
Creating artists specifically for adding to the legend (aka. Proxy artists)#
Not all handles can be turned into legend entries automatically, so it is often necessary to create an artist which can. Legend handles don't have to exist on the Figure or Axes in order to be used.
Suppose we wanted to create a legend which has an entry for some data which is represented by a red color:
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
fig, ax = plt.subplots()
red_patch = mpatches.Patch(color='red', label='The red data')
ax.legend(handles=[red_patch])
plt.show()