0
0
Matplotlibdata~5 mins

Text alignment options in Matplotlib

Choose your learning style9 modes available
Introduction

Text alignment helps place text exactly where you want it on a plot. It makes your charts easier to read and look neat.

When adding titles or labels to charts and you want them centered or aligned to the left or right.
When placing annotations on specific points in a graph and you want the text to not overlap with data points.
When creating legends or captions that need consistent alignment for better appearance.
When customizing tick labels on axes to improve readability.
When designing dashboards or reports with multiple plots and aligned text elements.
Syntax
Matplotlib
plt.text(x, y, 'text', ha='horizontal_alignment', va='vertical_alignment')
ha stands for horizontal alignment and can be 'left', 'center', or 'right'.
va stands for vertical alignment and can be 'top', 'center', 'bottom', or 'baseline'.
Examples
This places the text exactly centered at the point (0.5, 0.5).
Matplotlib
plt.text(0.5, 0.5, 'Center', ha='center', va='center')
The text's left top corner is placed at (0.5, 0.5).
Matplotlib
plt.text(0.5, 0.5, 'Left Top', ha='left', va='top')
The text's right bottom corner is placed at (0.5, 0.5).
Matplotlib
plt.text(0.5, 0.5, 'Right Bottom', ha='right', va='bottom')
Sample Program

This code creates a simple plot with three text labels placed at different vertical and horizontal alignments. You will see how the text aligns differently relative to the given coordinates.

Matplotlib
import matplotlib.pyplot as plt

plt.figure(figsize=(5, 3))
plt.xlim(0, 1)
plt.ylim(0, 1)

# Center aligned text
plt.text(0.5, 0.8, 'Center', ha='center', va='center', fontsize=12, color='blue')

# Left top aligned text
plt.text(0.5, 0.5, 'Left Top', ha='left', va='top', fontsize=12, color='green')

# Right bottom aligned text
plt.text(0.5, 0.2, 'Right Bottom', ha='right', va='bottom', fontsize=12, color='red')

plt.title('Text Alignment Options Example')
plt.show()
OutputSuccess
Important Notes

If you don't specify ha or va, the default is usually ha='left' and va='baseline'.

Use alignment options to avoid overlapping text and improve the visual clarity of your plots.

Summary

Text alignment controls where text appears relative to a point on the plot.

Use ha for horizontal and va for vertical alignment.

Proper alignment makes your charts easier to read and look professional.