0
0
Matplotlibdata~5 mins

Text placement with ax.text in Matplotlib

Choose your learning style9 modes available
Introduction

We use ax.text to add words or labels directly on a plot. This helps explain or highlight parts of the graph.

You want to label a specific point on a chart, like marking a peak or a special value.
You want to add a note or comment inside a plot area to explain something.
You want to show data values or categories directly on the graph for clarity.
You want to customize where text appears on a plot, not just in titles or axis labels.
Syntax
Matplotlib
ax.text(x, y, s, fontdict=None, **kwargs)

x and y are the coordinates where the text will appear.

s is the string of text you want to show.

Examples
Places the text 'Hello' at the point (2, 3) on the plot.
Matplotlib
ax.text(2, 3, 'Hello')
Places red text 'Center' at (0.5, 0.5) with bigger font size.
Matplotlib
ax.text(0.5, 0.5, 'Center', fontsize=14, color='red')
Aligns the text so its top-left corner is at (1, 1).
Matplotlib
ax.text(1, 1, 'Top Left', ha='left', va='top')
Sample Program

This code draws a simple line plot with points. It adds blue text labeling the point (1,1) and green text labeling the peak at (2,4). The text is placed exactly where we want on the plot.

Matplotlib
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([0, 1, 2], [0, 1, 4], marker='o')

# Add text at point (1,1)
ax.text(1, 1, 'Point (1,1)', fontsize=12, color='blue')

# Add text at coordinates (2,4) with center alignment
ax.text(2, 4, 'Peak', ha='center', va='bottom', fontsize=10, color='green')

plt.show()
OutputSuccess
Important Notes

You can control text alignment with ha (horizontal) and va (vertical) parameters.

Text color, font size, and style can be changed using keyword arguments like color and fontsize.

Coordinates are in data units by default, matching the plot's axes.

Summary

ax.text lets you add custom text anywhere on a plot.

You specify the position with x and y coordinates.

You can style the text with color, size, and alignment options.