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
Text alignment in a Matplotlib legend
Text alignment in a Matplotlib legend allows you to control how the legend text is positioned. You can set horizontal alignment using the set_ha() method on legend text objects.
Basic Legend Text Alignment
Here's how to align legend text to the left ?
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-5, 5, 100)
plt.plot(x, np.sin(x), label="$y=sin(x)$")
plt.plot(x, np.cos(x), label="$y=cos(x)$")
legend = plt.legend(loc='upper right')
for t in legend.get_texts():
t.set_ha('left')
plt.show()
Different Alignment Options
You can use various horizontal alignment values ?
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
x = np.linspace(-2, 2, 50)
alignments = ['left', 'center', 'right']
positions = ['upper left', 'upper center', 'upper right']
for i, (align, pos) in enumerate(zip(alignments, positions)):
axes[i].plot(x, np.sin(x), label="$y=sin(x)$")
axes[i].plot(x, np.cos(x), label="$y=cos(x)$")
legend = axes[i].legend(loc=pos)
for t in legend.get_texts():
t.set_ha(align)
axes[i].set_title(f'Alignment: {align}')
plt.tight_layout()
plt.show()
Alignment Options
| Alignment Value | Description | Text Position |
|---|---|---|
'left' |
Left-aligned | Text starts from the left edge |
'center' |
Center-aligned | Text centered (default) |
'right' |
Right-aligned | Text aligned to the right edge |
Customizing Legend Appearance
You can combine text alignment with other legend styling options ?
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), label="Sine wave", linewidth=2)
plt.plot(x, np.cos(x), label="Cosine wave", linewidth=2)
legend = plt.legend(loc='upper right', frameon=True, fancybox=True, shadow=True)
# Set text alignment and styling
for t in legend.get_texts():
t.set_ha('left')
t.set_fontsize(10)
plt.title('Legend with Left-Aligned Text')
plt.grid(True, alpha=0.3)
plt.show()
Conclusion
Use set_ha() method on legend text objects to control horizontal alignment. Combine with other styling options like frameon, shadow, and fancybox for better visual appearance.
Advertisements
