Legends

Legends#

Pandas plotting functions often handle legend creation, so we don’t have to do it manually.

But it’s useful to have some sense of what’s happening under the hood to build a legend.

Some key terms for working with Matplotlib’s .legend():

  • legend entry: exactly one key and one label

  • legend key: colored/patterned marker to the left of each legend label

  • legend label: text which describes the handle represented by the key

  • legend handle: original object used to generate an appropriate entry in the legend

.label()#

One way to build a legend is to use the label argument for each piece of the plot. Using .legend() means the elements to be added to the legend are determined automatically.

No additional arguments are passed to the function. Labels are set using the .set_label() method when creating the original handle.

Elements with an empty string as the label or a label that starts with the undescore character _ will not be included in the legend.

%matplotlib inline
import matplotlib.pyplot as plt # import statement

fig, ax = plt.subplots() # figure for new plot

line1, = plt.plot([1,2,3], label='Line 1') # first line
line2, = plt.plot([3,2,1], label='Line 2') # second line

plt.legend(handles=[line1, line2]) # create plot with legend

plt.show() # show output

We can also set labels separately using .set_label().

%matplotlib inline
import matplotlib.pyplot as plt # import statement

fig, ax = plt.subplots() # figure for new plot

line1, = plt.plot([1,2,3]) # first line
line2, = plt.plot([3,2,1]) # second line

line1.set_label("line1") # set line labels
line2.set_label("line2")

plt.legend(handles=[line1, line2]) # create plot with legend

plt.show() # show output

We could also create the labels manually as part of the .legend() argument.

%matplotlib inline
import matplotlib.pyplot as plt # import statement

fig, ax = plt.subplots() # figure for new plot

line1, = plt.plot([1,2,3]) # first line
line2, = plt.plot([3,2,1]) # second line

plt.legend(handles=[line1, line2], labels=['Line 1', 'Line 2']) # create plot with legend and labels

plt.show() # show output

Additional Resources#

There’s a lot of additional legend functionality we’re not covering, including customizing location, anchoring the legend in the figure, handling color style and marker, etc.

For more on these parameters and other .legend() customization options: