- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to get all the legends from a plot in Matplotlib?
To get all the legends from a plot in matplotlib, we can use the get_children() method to get all the properties of an axis, then iterate all the properties. If an item is an instance of a Legend, then get the legend texts.
steps
Set the figure size and adjust the padding between and around the subplots.
Create x data points using numpy.
Create a figure and a set of subplots.
Plot sin(x) and cos(x) using plot() method with different labels and colors.
Get the children of the axis and get the texts of the legend.
To display the figure, use show() method.
Example
import numpy as np from matplotlib import pyplot as plt import matplotlib plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = np.linspace(-10, 10, 100) fig, ax = plt.subplots() ax.plot(np.sin(x), color='red', lw=7, label="y=sin(x)") ax.plot(np.cos(x), color='orange', lw=7, label="y=cos(x)") plt.legend(loc='upper right') for item in ax.get_children(): if isinstance(item, matplotlib.legend.Legend): print(item.texts) plt.show()
Output
- Related Articles
- How to plot data from multiple two-column text files with legends in Matplotlib?
- How to plot two Pandas time series on the same plot with legends and secondary Y-axis in Matplotlib?
- How to get a Gantt plot using matplotlib?
- Matplotlib legends in subplot
- How to surface plot/3D plot from a dataframe (Matplotlib)?
- How to get a matplotlib Axes instance to plot to?
- How to extract data from a Matplotlib plot?
- How to plot a line graph from histogram data in Matplotlib?
- How to a plot stem plot in Matplotlib Python?
- How to plot a bar graph in Matplotlib from a Pandas series?
- How to plot a Pandas multi-index dataFrame with all xticks (Matplotlib)?
- How to get coordinates from the contour in matplotlib?
- Drawing multiple legends on the same axes in Matplotlib
- How to plot a circle in Matplotlib?
- How to plot histograms from dataframes in Pandas using Matplotlib?

Advertisements