Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Matplotlib legend() Function

Matplotlib legend() Function


Matplotlib Reference Documentation Matplotlib Reference Documentation

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

Function definition

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

Common parameters

Parameters Type Description
loc str or int Legend location: 'best' (automatic), 'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center', 'outside'
bbox_to_anchor tuple Legend anchor coordinates, used with loc for precise positioning. For example, (1.05, 1) places the legend at the upper-right outside the Axes
ncol int Number of legend columns, default 1. Multiple entries are displayed in multiple columns
fontsize int or str Legend font size, such as 10, 'small', 'large'
frameon bool Whether to show the legend frame, default True
shadow bool Whether to add a shadow effect
title str Title of the legend
facecolor color Legend background color
edgecolor color Legend frame color
fancybox bool Whether to use rounded corners for the frame, default True
markerscale float Scaling of markers in the legend relative to the original markers
handlelength float Length of lines in the legend

The legend only shows Artists with the label parameter 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'

)

Each curve's label 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

)

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'

)

Plot 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 outside

          ncol

=

2

,

                     

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: Quick reference for legend location codes

Example

import

matplotlib.

pyplot

as

plt

Show 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

(

)


Common questions

Legend not showing?

Check whether the plotting function set the label parameter was added.

Confirm that legend() function in Vue 3.

If some Artists don't need to appear in the legend, set their label to an empty string or 'nolegend'。

How to locally modify the line style in the legend?

Pass legend.get_lines() Get the line objects in the legend and modify their properties, or use handler_map parameter was added.

Matplotlib Reference Documentation Matplotlib Reference Documentation