Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 through them. If an item is an instance of a Legend, we can extract the legend texts.
Steps
Set the figure size and adjust the padding between 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 extract the texts of the legend.
Display the figure using show() method.
Example
Here's how to extract all legend information from a matplotlib plot ?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
# Set figure parameters
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create data points
x = np.linspace(-10, 10, 100)
fig, ax = plt.subplots()
# Plot functions with labels
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)")
# Create legend
plt.legend(loc='upper right')
# Get all legend texts from the plot
for item in ax.get_children():
if isinstance(item, matplotlib.legend.Legend):
print("Legend texts:", [text.get_text() for text in item.texts])
plt.show()
The output will show the legend texts and display the plot ?
Legend texts: ['y=sin(x)', 'y=cos(x)']
Alternative Method Using get_legend()
You can also directly access the legend using the get_legend() method ?
import numpy as np
import matplotlib.pyplot as plt
# Create sample plot
x = np.linspace(-10, 10, 100)
fig, ax = plt.subplots()
ax.plot(np.sin(x), color='red', label="sine")
ax.plot(np.cos(x), color='blue', label="cosine")
ax.plot(np.tan(x), color='green', label="tangent")
plt.legend()
# Get legend directly
legend = ax.get_legend()
if legend:
legend_labels = [text.get_text() for text in legend.get_texts()]
print("Legend labels:", legend_labels)
plt.ylim(-2, 2) # Limit y-axis for better visualization
plt.show()
Legend labels: ['sine', 'cosine', 'tangent']
Comparison
| Method | Approach | Best For |
|---|---|---|
get_children() |
Iterate through all axis children | Multiple legends or complex plots |
get_legend() |
Direct legend access | Simple plots with single legend |
Conclusion
Use get_legend() for direct access to a single legend, or get_children() when you need to find all legends in complex plots. Both methods allow you to extract legend text and properties programmatically.
