0% found this document useful (0 votes)
20 views2 pages

Using plt.legend() in Matplotlib

The legend() function in matplotlib is used to place a legend on the axes. It takes attributes like loc to specify the legend location, bbox_to_anchor to specify coordinates, and ncol for number of columns. Other attributes include shadow, markerscale, numpoints, fontsize, facecolor, and edgecolor.

Uploaded by

Smriti Sharma
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views2 pages

Using plt.legend() in Matplotlib

The legend() function in matplotlib is used to place a legend on the axes. It takes attributes like loc to specify the legend location, bbox_to_anchor to specify coordinates, and ncol for number of columns. Other attributes include shadow, markerscale, numpoints, fontsize, facecolor, and edgecolor.

Uploaded by

Smriti Sharma
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

[Link].

legend()
A legend is an area describing the elements of the graph. In the matplotlib library,
there’s a function called legend() which is used to Place a legend on the axes.
The attribute Loc in legend() is used to specify the location of the [Link]
value of loc is loc=”best” (upper left). The strings ‘upper left’, ‘upper right’, ‘lower
left’, ‘lower right’ place the legend at the corresponding corner of the axes/figure.
The attribute bbox_to_anchor=(x, y) of legend() function is used to specify the
coordinates of the legend, and the attribute ncol represents the number of columns
that the legend [Link]’s default value is 1.

Syntax:
[Link]([“blue”, “green”], bbox_to_anchor=(0.75, 1.15), ncol=2)
The Following are some more attributes of function legend() :
 shadow: [None or bool] Whether to draw a shadow behind the [Link]’s
Default value is None.
 markerscale: [None or int or float] The relative size of legend markers
compared with the originally drawn [Link] Default is None.
 numpoints: [None or int] The number of marker points in the legend
when creating a legend entry for a Line2D (line).The Default is None.
 fontsize: The font size of the [Link] the value is numeric the size will
be the absolute font size in points.
 facecolor: [None or “inherit” or color] The legend’s background color.
 edgecolor: [None or “inherit” or color] The legend’s background patch
edge color.
Ways to use legend() function in Python –
Example 1:
import numpy as np
import [Link] as plt

# X-axis values
x = [1, 2, 3, 4, 5]

# Y-axis values
y = [1, 4, 9, 16, 25]

# Function to plot
[Link](x, y)

# Function add a legend


[Link](['single element'])

# function to show the plot


[Link]()
Output :

You might also like