Matplotlib legend() Function


Matplotlib 参考文档Matplotlib Reference Documentation

legend()Used to add a legend to a chart, helping readers identify the meaning of each curve or group of data.

Function Definition

matplotlib.pyplot.legend(*args, **kwargs)
Axes.legend(*args, **kwargs)
Figure.legend(*args, **kwargs)

Common Parameter Descriptions

ParameterTypeDescription
locstr or intLegend position: 'best' (automatic), 'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center', 'outside'
bbox_to_anchortupleLegend anchor coordinates, used with loc for precise positioning. For example, (1.05, 1) places the legend at the upper right corner outside the Axes.
ncolintNumber of legend columns, default is 1. When there are multiple entries, they are displayed in multiple columns.
fontsizeint or strLegend font size, e.g., 10, 'small', 'large'
frameonboolWhether to show the legend frame, default True
shadowboolWhether to add a shadow effect
titlestrThe title of the legend
facecolorcolorLegend background color
edgecolorcolorLegend frame color
fancyboxboolWhether to use a rounded frame, default True
markerscalefloatThe scale of markers in the legend relative to the original markers
handlelengthfloatThe length of lines in the legend

The legend only displays Artists that have thelabelparameter set. A common practice is to specify label directly in plotting functions such as plot(), scatter(), bar(), and then call legend().


Usage Examples

Example 1: Basic Legend

Example

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

fig, ax = plt.subplots(layout='constrained')

# The label of each curve automatically enters the legend
ax.plot(x, np.sin(x), label='sin(x)')
ax.plot(x, np.cos(x), label='cos(x)')
ax.plot(x, np.sin(x) * np.exp(-x/3), label='damped sin(x)')

ax.legend(loc='upper right')  # Automatically collect all labels
ax.set_title('Basic Legend')
ax.set_xlabel('x')
ax.grid(True, alpha=0.3)
plt.show()

Example 2: Legend Outside the Chart + Multiple Columns

Example

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

fig, ax = plt.subplots(figsize=(8, 4), layout='constrained')

# Draw multiple curves
for i in range(6):
    ax.plot(x, np.sin(x + i * 0.5), label=f'sin(x + {i*0.5:.1f})')

# Place the legend outside the Axes, displayed in two columns
ax.legend(loc='upper left',
          bbox_to_anchor=(1.02, 1),   # Upper right corner outside
          ncol=2,                      # Split into two columns
          title='Phase Shift',
          frameon=True,
          fancybox=True,
          shadow=True)

ax.set_title('Legend Outside the Plot (ncol=2)')
ax.set_xlabel('x')
ax.grid(True, alpha=0.3)
plt.show()

Example 3: Custom Legend Entries

Example

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np

x = np.linspace(0, 10, 100)

fig, ax = plt.subplots(layout='constrained')

ax.plot(x, np.sin(x), 'b-', linewidth=2)
ax.plot(x, np.cos(x), 'r--', linewidth=2)

# Manually specify legend entries (not associated with plot labels)
blue_line = mpatches.Patch(color='blue', label='Sine Wave')
red_line = mpatches.Patch(color='red', label='Cosine Wave')

ax.legend(handles=[blue_line, red_line],
          loc='upper right',
          fontsize=11)

ax.set_title('Custom Legend Handles')
ax.set_xlabel('x')
ax.grid(True, alpha=0.3)
plt.show()

Example 4: Legend Location Code Quick Reference

Example

import matplotlib.pyplot as plt

# Display the positions corresponding to all loc codes
locations = [
    'upper left', 'upper right', 'lower left', 'lower right',
    'center left', 'center right', 'lower center', 'upper center',
    'center'
]

fig, axes = plt.subplots(3, 3, figsize=(10, 8),
                          layout='constrained')
axes = axes.flatten()

for ax, loc in zip(axes, locations):
    ax.plot([0, 1], [0, 1], 'b-', label='Line A')
    ax.plot([0, 1], [1, 0], 'r--', label='Line B')
    ax.legend(loc=loc, fontsize=8, title=f'loc="{loc}"')
    ax.set_xticks([])
    ax.set_yticks([])

fig.suptitle('All legend() Locations', fontsize=14)
plt.show()

Frequently Asked Questions

Legend not showing?

Check whether the plotting function has thelabelparameter set.

Make sure you called thelegend()function.

If some Artists do not need to appear in the legend, set label to an empty string or '_nolegend_'.

How to partially modify the line styles in the legend?

Uselegend.get_lines()to get the line objects in the legend and modify their properties, or use thehandler_mapparameter.


Matplotlib 参考文档Matplotlib Reference Documentation

Other Extensions