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:

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels)

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():

fig, ax = plt.subplots()
line_up, = ax.plot([1, 2, 3], label='Line 2')
line_down, = ax.plot([3, 2, 1], label='Line 1')
ax.legend(handles=[line_up, line_down])

Renaming legend entries#

When the labels cannot directly be set on the handles, they can be directly passed to Axes.legend:

fig, ax = plt.subplots()
line_up, = ax.plot([1, 2, 3], label='Line 2')
line_down, = ax.plot([3, 2, 1], label='Line 1')
ax.legend([line_up, line_down], ['Line Up', 'Line Down'])

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:

my_map = {'Line Up':'Up', 'Line Down':'Down'}

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, [my_map[l] for l in 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()