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
Show only certain items in legend Python Matplotlib
In Python Matplotlib, you can control which items appear in the legend by using the plt.legend() method with a list of labels. This allows you to show only specific plot elements in the legend rather than all plotted data.
Basic Syntax
The plt.legend() method accepts a list of labels to display ?
plt.legend(["label1", "label2"], loc=location, frameon=True/False)
Parameters
labels − List of strings to show in the legend
loc − Location of the legend (0 for best location)
frameon − Boolean flag to show/hide legend border
Example
Here's how to create a plot with multiple lines and show only selected items in the legend ?
import matplotlib.pyplot as plt
# Set axis labels
plt.ylabel("Y-axis")
plt.xlabel("X-axis")
# Plot multiple lines
plt.plot([1, 2, 3], [9, 5, 2], 'b-') # Blue line
plt.plot([1, 2, 3], [2, 5, 8], 'r-') # Red line
plt.plot([1, 2, 3], [4, 7, 8], 'g-') # Green line
# Show only specific items in legend
location = 0 # Best location
legend_drawn_flag = True
plt.legend(["Blue Line", "Red Line"], loc=location, frameon=legend_drawn_flag)
plt.show()
In this example, even though we plotted three lines, only two items ("Blue Line" and "Red Line") appear in the legend. The green line is plotted but not included in the legend.
Using Handle-Label Approach
For more control, you can specify which plot handles to include ?
import matplotlib.pyplot as plt
# Create plots and store handles
line1, = plt.plot([1, 2, 3], [1, 4, 2], 'b-', label='Series A')
line2, = plt.plot([1, 2, 3], [2, 3, 1], 'r-', label='Series B')
line3, = plt.plot([1, 2, 3], [3, 1, 4], 'g-', label='Series C')
# Show only selected handles in legend
plt.legend(handles=[line1, line3], labels=['First Series', 'Third Series'])
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
This approach gives you precise control over which plot elements appear in the legend and what labels they display.
Key Points
Legend labels list should match the order of plotted elements
You can show fewer legend items than plotted lines
Use
loc=0for automatic best positioningSet
frameon=Falseto remove legend border
Conclusion
Use plt.legend() with a labels list to show only specific items in your plot legend. This helps create cleaner visualizations by displaying only the most important plot elements to your audience.
