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 do you just show the text label in a plot legend in Matplotlib?
When creating matplotlib plots with legends, you might want to display only the text labels without the colored lines or markers. This can be achieved using specific parameters in the legend() method to hide the legend handles.
Basic Approach
To show only text labels in a plot legend, use the legend() method with these key parameters:
- handlelength=0 − Sets the length of legend handles to zero
- handletextpad=0 − Removes padding between handle and text
- fancybox=False − Uses simple rectangular legend box
Example
Here's how to create a plot with text-only legend labels ?
import numpy as np import matplotlib.pyplot as plt # Set figure size plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True # Create random data x = np.random.rand(100) y = np.random.rand(100) # Create plot fig, ax = plt.subplots() ax.plot(x, y, label='Zig-Zag', c="red") # Add legend with text only ax.legend(loc="upper right", handlelength=0, handletextpad=0, fancybox=False) plt.show()
Multiple Data Series Example
This approach works well when you have multiple data series and want clean text labels ?
import numpy as np
import matplotlib.pyplot as plt
# Create sample data
x = np.linspace(0, 10, 50)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.sin(x + np.pi/4)
# Create plot with multiple series
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(x, y1, label='Sine Wave', color='blue')
ax.plot(x, y2, label='Cosine Wave', color='red')
ax.plot(x, y3, label='Phase Shifted', color='green')
# Text-only legend
ax.legend(handlelength=0, handletextpad=0, fancybox=False,
loc='upper right', frameon=True)
plt.title('Trigonometric Functions')
plt.show()
Key Parameters
| Parameter | Value | Purpose |
|---|---|---|
handlelength |
0 | Removes the colored line/marker |
handletextpad |
0 | Eliminates space between handle and text |
fancybox |
False | Uses simple rectangular legend box |
Conclusion
Use handlelength=0 and handletextpad=0 to display only text labels in matplotlib legends. This creates cleaner legends when the visual indicators aren't necessary for understanding the plot.
Advertisements
