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 set legend marker size and alpha in Matplotlib?
In Matplotlib, you can customize the appearance of legend markers by adjusting their size and transparency (alpha) independently from the plot markers. This is useful when you want the legend to be more readable while maintaining the original plot styling.
Setting Legend Marker Properties
After creating a legend, access the legend handles and modify the marker properties using _legmarker attributes ?
import matplotlib.pyplot as plt
import numpy as np
# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Generate sample data
N = 10
x = np.random.rand(N)
y = np.random.rand(N)
# Plot with marker styling
line, = plt.plot(x, y, marker='*', markersize=20, markeredgecolor='black',
alpha=0.4, ls='none', label='Random Data')
# Create legend and customize marker
legend = plt.legend(loc='upper right')
legend.legendHandles[0]._legmarker.set_markersize(15)
legend.legendHandles[0]._legmarker.set_alpha(1)
plt.show()
Alternative Approach Using Legend Parameters
You can also set legend marker properties directly when creating the legend using the markerscale parameter ?
import matplotlib.pyplot as plt
import numpy as np
# Generate data
x = np.random.rand(10)
y = np.random.rand(10)
# Plot data
plt.plot(x, y, marker='o', markersize=10, alpha=0.5,
linestyle='none', label='Data Points')
# Create legend with scaled markers
legend = plt.legend(markerscale=2, loc='upper right')
# Set alpha for legend markers
for handle in legend.legendHandles:
handle._legmarker.set_alpha(1.0)
plt.title('Legend with Custom Marker Size and Alpha')
plt.show()
Key Properties
| Property | Method | Description |
|---|---|---|
| Marker Size | set_markersize() |
Sets absolute marker size in points |
| Alpha | set_alpha() |
Sets transparency (0=transparent, 1=opaque) |
| Scale | markerscale |
Scales markers relative to plot markers |
Output
The customized legend will display markers with the specified size and alpha values, making them more visible and distinguishable from the plot markers.
Conclusion
Use _legmarker.set_markersize() and _legmarker.set_alpha() to customize legend markers independently from plot markers. The markerscale parameter provides a convenient way to scale legend markers relative to the original plot markers.
