Matplotlib.pyplot.text() function in Python
matplotlib.pyplot.text() function in Python is used to add text to the axes at a specific location (x, y) in data coordinates. It is commonly used to annotate plots with labels, notes or mathematical equations.
Syntax:
matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)
Parameters:
| Parameter | Description |
| x, y:float | The position to place the text. By default, this is in data coordinates. The coordinate system can be changed using the transform parameter. |
| s :str | The text. |
| fontdict : dict default none | A dictionary to override the default text properties. If fontdict is None, the defaults are determined by rcParams. |
| **kwargs | Text properties. |
Example 1: Text on plot sheet
import matplotlib.pyplot
matplotlib.pyplot.text(0.5, 0.5, "Hello World!")
plt.show()
Output:

Explanation:
- (0.5, 0.5): Position of the text (center of the default axes).
- "Hello World!": The text displayed.
- fontsize=14, color="blue": Custom text properties.
- ha='center', va='center': Aligns text at its center relative to (x, y).
Example 2: Add text to a plot
import matplotlib.pyplot as plt
w = 4
h = 3
d = 70
plt.figure(figsize=(w, h), dpi=d)
x = [1, 2, 4]
x_pos = 0.5
y_pos = 3
plt.text(x_pos, y_pos, "text on plot")
plt.plot(x)
plt.show()
Output:

Explanation:
- plt.plot(x) : Plots a green line with points [1, 2, 4].
- plt.text(x_pos, y_pos, "Text on plot", ...): Places red text at (0.5, 3).
- ha='left', va='bottom': Aligns the text relative to the given coordinates.
- rotation=10: Slightly tilts the text.