The Wayback Machine - https://web.archive.org/web/20241120003302/https://www.geeksforgeeks.org/matplotlib-pyplot-legend-in-python/
Open In App

Matplotlib.pyplot.legend() in Python

Last Updated : 01 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. In this article, we will learn about the Matplotlib Legends.

Python Matplotlib.pyplot.legend() Syntax

Syntax: matplotlib.pyplot.legend([“blue”, “green”], bbox_to_anchor=(0.75, 1.15), ncol=2)

Attributes:

  • shadow: [None or bool] Whether to draw a shadow behind the legend.It’s Default value is None.
  • markerscale: [None or int or float] The relative size of legend markers compared with the originally drawn ones.The 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 legend.If 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.

Matplotlib.pyplot.legend() in Python

Matplotlib.pyplot.legend() function is a utility given in the Matplotlib library for Python that gives a way to label and differentiate between multiple plots in the same figure

The attribute Loc in legend() is used to specify the location of the legend. The default value of loc is loc= “best” (upper left). The strings ‘upper left’, ‘upper right’, ‘lower left’, and ‘lower right’ place the legend at the corresponding corner of the axes/figure.

The attribute bbox_to_anchor=(x, y) of the legend() function is used to specify the coordinates of the legend, and the attribute ncol represents the number of columns that the legend has. Its default value is 1.

Python Matplotlib legend() Function Examples

Below are some examples that can see the Matplotlib interactive mode setup using Matplotlib.pyplot.legend() in Python:

Add a Legend to a Matplotlib

In this example, a simple quadratic function \( y = x^2 \) is plotted against the x-values [1, 2, 3, 4, 5]. A legend labeled “single element” is added to the plot, clarifying the plotted data.

Python
import numpy as np 
import matplotlib.pyplot as plt 

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

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

# Function to plot 
plt.plot(x, y) 

# Function add a legend 
plt.legend(['single element']) 

# function to show the plot 
plt.show() 

Output :

graph

Change the Position of the Legend

In this example, two data series, represented by `y1` and `y2`, are plotted. Each series is differentiated by a specific color, and the legend provides color-based labels “blue” and “green” for clarity.

Python
# importing modules
import numpy as np
import matplotlib.pyplot as plt

# Y-axis values
y1 = [2, 3, 4.5]

# Y-axis values
y2 = [1, 1.5, 5]

# Function to plot
plt.plot(y1)
plt.plot(y2)

# Function add a legend
plt.legend(["blue", "green"], loc="lower right")

# function to show the plot
plt.show()

Output :

graph

Combine Multiple labels in legend

In this example, two curves representing `y1` and `y2` are plotted against the `x` values. Each curve is labeled with a distinct legend entry, “Numbers” and “Square of numbers”, respectively, providing clarity to the viewer.

Python
import numpy as np
import matplotlib.pyplot as plt

# X-axis values
x = np.arange(5)

# Y-axis values
y1 = [1, 2, 3, 4, 5]

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

# Function to plot
plt.plot(x, y1, label='Numbers')
plt.plot(x, y2, label='Square of numbers')

# Function add a legend
plt.legend()

# function to show the plot
plt.show()

Output :

graph

Plotting Sine and Cosine Functions with Legends in Matplotlib

In this example, both the sine and cosine functions are plotted against the range [0, 10] on the x-axis. The plot includes legends distinguishing the sine and cosine curves, enhancing visual clarity.

Python
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 1000)
fig, ax = plt.subplots()

ax.plot(x, np.sin(x), '--b', label='Sine')
ax.plot(x, np.cos(x), c='r', label='Cosine')
ax.axis('equal')

leg = ax.legend(loc="lower left")

Output:

Place the Legend Outside the Plot in Matplotlib

In this example, two functions y = x and y = 3x are plotted against the x-values. The legend is strategically positioned above the plot with two columns for improved layout and clarity.

Python
# importing modules
import numpy as np
import matplotlib.pyplot as plt

# X-axis values
x = [0, 1, 2, 3, 4, 5, 6, 7, 8]

# Y-axis values
y1 = [0, 3, 6, 9, 12, 15, 18, 21, 24]
# Y-axis values
y2 = [0, 1, 2, 3, 4, 5, 6, 7, 8]

# Function to plot
plt.plot(y1, label="y = x")
plt.plot(y2, label="y = 3x")

# Function add a legend
plt.legend(bbox_to_anchor=(0.75, 1.15), ncol=2)
plt.show()

Output:

graph


Matplotlib.pyplot.legend() in Python – FAQs

How to create a legend in Matplotlib?

To create a legend in Matplotlib, you can use the legend() function after plotting your data. This function adds a legend to your plot, which helps to identify different data series.

import matplotlib.pyplot as plt

# Plot data
plt.plot([1, 2, 3], [4, 5, 6], label='Line 1')
plt.plot([1, 2, 3], [6, 5, 4], label='Line 2')

# Create a legend
plt.legend()

# Show the plot
plt.show()

What is Matplotlib Pyplot in Python?

matplotlib.pyplot is a collection of functions that make Matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.

import matplotlib.pyplot as plt

# Create a simple plot
plt.plot([1, 2, 3], [4, 5, 6])
plt.title('Simple Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

How to remove legend entries in Matplotlib?

To remove specific legend entries, you can exclude the label parameter or set it to _nolegend_ when plotting the data you don’t want in the legend.

import matplotlib.pyplot as plt

# Plot data
plt.plot([1, 2, 3], [4, 5, 6], label='Line 1')
plt.plot([1, 2, 3], [6, 5, 4], label='_nolegend_')
plt.plot([1, 2, 3], [5, 5, 5], label='Line 3')

# Create a legend
plt.legend()

# Show the plot
plt.show()

Which function is used to show legend in Matplotlib?

The legend() function is used to display the legend in Matplotlib.

import matplotlib.pyplot as plt

# Plot data
plt.plot([1, 2, 3], [4, 5, 6], label='Line 1')
plt.plot([1, 2, 3], [6, 5, 4], label='Line 2')

# Show the legend
plt.legend()

# Show the plot
plt.show()

What does legend() do in Python?

The legend() function in Matplotlib adds a legend to the plot. The legend helps to identify different data series by using labels specified in the label parameter of the plot functions.

import matplotlib.pyplot as plt

# Plot data with labels
plt.plot([1, 2, 3], [4, 5, 6], label='Line 1')
plt.plot([1, 2, 3], [6, 5, 4], label='Line 2')

# Add a legend
plt.legend()

# Show the plot
plt.show()

The legend() function displays a box with descriptions of each plot, using the labels provided in the label parameter of the plotting functions.



Previous Article
Next Article

Similar Reads

How to manually add a legend color and legend font size on a plotly figure in Python?
In this article, we will learn how to manually add a legend color and legend font size on a plotly figure in Python. A legend is an area describing the elements of the graph. In the plotly legend is used to Place a legend on the axes. Here we will discuss different methods for manually adding legend color and legend font size in plotly express, usi
2 min read
Matplotlib.axes.Axes.legend() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. matplotlib.axes.Axes.legend() Function The Axes.le
2 min read
Matplotlib.figure.Figure.legend() in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements. matplotlib.figure.Figure.legend() metho
2 min read
Matplotlib.pyplot.broken_barh() in Python
Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays. Pyplot is a collection of command style functions that make matplotlib work like MATLAB. matplotlib.pyplot.broken_barh() The function broken_barh() is used to Plot a horizontal sequence of rectan
2 min read
Matplotlib.pyplot.axis() in Python
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Pyplot is a Matplotlib module which provides a MATLAB-like interface. Matplotlib is designed to be as usable as MATLAB, with the ability to use Python and the advantage of being free and open-source. matplotlib.pyplot.axis() This function is us
1 min read
Matplotlib.pyplot.get_fignums() in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. matplotlib.pyplot.get_fignums() method The ge
2 min read
Python | Matplotlib.pyplot ticks
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2003.One of the greatest benefits of visualization is that it allows us visual access to huge
3 min read
Matplotlib.pyplot.waitforbuttonpress() in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. matplotlib.pyplot.waitforbuttonpress() method
2 min read
Matplotlib.pyplot.streamplot() in Python
Stream plot is basically a type of 2D plot used majorly by physicists to show fluid flow and 2D field gradients .The basic function to create a stream plot in Matplotlib is: ax.streamplot(x_grid, y_grid, x_vec, y_vec, density=spacing) Here x_grid and y_grid are arrays of the x and y points.The x_vec and y_vec represent the stream velocity of each p
7 min read
Matplotlib.pyplot.ylim() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.ylim() Function The ylim() function in pyplot module of matplotlib library is used to get or set the y-limits of the current axes. Syntax
2 min read
Matplotlib.pyplot.figimage() function in Python
Matplotlib is a widely used library in Python for plotting various graphs, as it provides very efficient ways and easy to understand methods for complex plots also. pyplot is a collection of command style functions that make matplotlib work like MATLAB. figimage() function matplotlib.pyplot.figimage() is a method for adding a non-resampled image to
2 min read
matplotlib.pyplot.arrow() in Python
Matplotlib is a very powerful plotting library useful for those working with Python and NumPy. And for making statistical interference, it becomes very necessary to visualize our data and Matplotlib is the tool that can be very helpful for this purpose. It provides MATLAB like interface only difference is that it uses Python and is open source. mat
2 min read
Matplotlib.pyplot.ylabel() in Python
Matplotlib is a very powerful plotting library useful for those working with Python and NumPy. And for making statistical interference, it becomes very necessary to visualize our data and Matplotlib is the tool that can be very helpful for this purpose. matplotlib.pyplot.ylabel() This function sets the label for the y-axis of the plot. Syntax: matp
2 min read
Matplotlib.pyplot.acorr() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.acorr() Function The acorr() function in pyplot module of matplotlib library is used to plot the autocorrelation of x (array-like). Synta
2 min read
matplotlib.pyplot.angle_spectrum() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.acorr() Function: The angle_spectrum() function in pyplot module of matplotlib library is used to plot the angle spectrum. Generally, it
2 min read
Matplotlib.pyplot.thetagrids() in Python
Matplotlib is a plotting library of Python programming language and its numerical mathematics module is NumPy. matplotlib.pyplot is a collection of command style functions that make matplotlib work like the MATLAB Tool. Each of the pyplot functions makes certain changes to a figure: e.g., creating a figure, creating a plot area in a figure, plots s
2 min read
matplotlib.pyplot.axhline() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.axhline() Function The axhline() function in pyplot module of matplotlib library is used to add a horizontal line across the axis. Syntax
2 min read
Matplotlib.pyplot.vlines() in Python
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Matplotlib.pyplot.vlines() matplotlib.pyplot.vlines() is a function used in the plotting of a dataset. In matplotlib.pyplot.vlines(), vlines is the abbreviation for vertical lines.what this function does is very much clear from the expanded for
2 min read
Matplotlib.pyplot.yticks() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. Matplotlib.pyplot.yticks() Function The annotate() function in pyplot module of matplotlib library is used to get and set the current tick locations and la
2 min read
Matplotlib.pyplot.annotate() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.annotate() Function The annotate() function in pyplot module of matplotlib library is used to annotate the point xy with text s. Syntax:
3 min read
Matplotlib.pyplot.xticks() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.xticks() Function The annotate() function in pyplot module of matplotlib library is used to get and set the current tick locations and la
2 min read
Matplotlib.pyplot.xlabels() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.xlabel() Function The xlabel() function in pyplot module of matplotlib library is used to set the label for the x-axis.. Syntax: matplotl
2 min read
Matplotlib.pyplot.ylabels() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.ylabel() Function The ylabel() function in pyplot module of matplotlib library is used to set the label for the x-axis.. Syntax: matplotl
2 min read
Matplotlib.pyplot.barbs() in Python
Matplotlib is a library of Python bindings which provides the user with a MATLAB-like plotting framework. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc. Note: For more information, refer to Python Matplotlib – An Overview Ma
3 min read
Matplotlib.pyplot.axvspan() in Python
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python.\ Pyplot is a Matplotlib module which provides a MATLAB-like interface. Matplotlib is designed to be as usable as MATLAB, with the ability to use Python and the advantage of being free and open-source. matplotlib.pyplot.axvspan() This function s
2 min read
Matplotlib.pyplot.locator_params() in Python
Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays.Pyplot is a collection of command style functions that make matplotlib work like MATLAB. Note: For more information, refer to Python Matplotlib – An Overview locator_params() is used for controlli
2 min read
Matplotlib.pyplot.stackplot() in Python
Matplotlib is a visualization library available in Python. Pyplot contains various functions that help matplotlib behave like MATLAB. It is used as matplotlib.pyplot for plotting figures, creating areas, lines, etc. Stackplot Among so many functions provided by pyplot one is stackplot which will be discussed in this article. Stackplot is used to dr
3 min read
Matplotlib.pyplot.xkcd() in Python
One of the main process in Data Science is Data Visualization. Data Visualization refers to present a dataset in the form of graphs and pictures. We can identify upcoming trend by observing these Graphs. Python provides us with an amazing Data Visualization library in it which is Matplotlib which was developed by John Hunter (1968-2012). Matplotlib
2 min read
Matplotlib.pyplot.axvline() in Python
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc. Note: For more information, refer to Python Matplotlib – An Overview Py
2 min read
Matplotlib.pyplot.stem() in Python
Matplotlib is a visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.pyplot.stem() matplotlib.pyplot.stem() creates stem plots. A Stem plot plots vertical lines at each x position covered under the graph f
3 min read
Practice Tags :
three90RightbarBannerImg