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
Selected Reading
How to make several legend keys to the same entry in Matplotlib?
In Matplotlib, you can create a legend entry with multiple keys (symbols) representing different lines or data series. This is useful when you want to group related plots under a single legend label.
Basic Approach
Use the HandlerTuple class to group multiple plot objects under one legend entry ?
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create two different line plots
p1, = plt.plot([1, 2.5, 3], 'r-d', label='Red line')
p2, = plt.plot([3, 2, 1], 'k-o', label='Black line')
# Create legend with both keys for single entry
legend = plt.legend([(p1, p2)], ['Two keys'], numpoints=1,
handler_map={tuple: HandlerTuple(ndivide=None)})
plt.show()
Multiple Legend Entries with Multiple Keys
You can create several legend entries, each with multiple keys ?
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple
# Create multiple plots
line1, = plt.plot([1, 2, 3], 'r-o', markersize=8)
line2, = plt.plot([1, 2, 3], 'r--', linewidth=2)
line3, = plt.plot([3, 2, 1], 'b-s', markersize=8)
line4, = plt.plot([3, 2, 1], 'b:', linewidth=2)
# Create legend with multiple entries, each having multiple keys
plt.legend([(line1, line2), (line3, line4)],
['Red Group', 'Blue Group'],
handler_map={tuple: HandlerTuple(ndivide=None)})
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Legend with Multiple Keys per Entry')
plt.show()
Customizing Handler Spacing
Control the spacing between keys using the ndivide parameter ?
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple
p1, = plt.plot([1, 2.5, 3], 'r-d', markersize=10)
p2, = plt.plot([3, 2, 1], 'g-o', markersize=10)
p3, = plt.plot([2, 1.5, 2.5], 'b-^', markersize=10)
# Different spacing options
plt.legend([(p1, p2, p3)], ['Three keys with custom spacing'],
handler_map={tuple: HandlerTuple(ndivide=2)},
loc='upper right')
plt.grid(True, alpha=0.3)
plt.show()
Parameters
| Parameter | Description | Example Value |
|---|---|---|
ndivide |
Controls spacing between legend keys |
None, 1, 2
|
numpoints |
Number of marker points in legend |
1, 2
|
handler_map |
Maps object types to legend handlers | {tuple: HandlerTuple()} |
Conclusion
Use HandlerTuple with tuples of plot objects to create legend entries with multiple keys. This technique is perfect for grouping related data series under single legend labels.
Advertisements
