Matplotlib text() / annotate() Function
Matplotlib Reference Documentation
text()Add text at specified coordinates in the chart,annotate()Add annotations with arrows, which can precisely point to data points.
Function Definition
text()
matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs) Axes.text(x, y, s, fontdict=None, **kwargs)
annotate()
matplotlib.pyplot.annotate(text, xy, xytext=None, xycoords='data',
textcoords=None, arrowprops=None, annotation_clip=None, **kwargs)
Axes.annotate(text, xy, xytext=None, xycoords='data',
textcoords=None, arrowprops=None, annotation_clip=None, **kwargs)
Parameter Description
text() Parameters
| Parameter | Description |
|---|---|
| x, y | Text position coordinates |
| s | The text string to display |
| fontsize | Font size |
| color | Text color |
| ha / horizontalalignment | Horizontal alignment: 'center', 'right', 'left' |
| va / verticalalignment | Vertical alignment: 'center', 'top', 'bottom', 'baseline' |
| rotation | Rotation angle (degrees) |
| fontweight | Font weight: 'normal', 'bold', 'light' |
| bbox | Text background box properties, e.g., dict(facecolor='yellow', alpha=0.5) |
annotate() Specific Parameters
| Parameter | Description |
|---|---|
| text | Annotation text content |
| xy | Coordinates of the target point being pointed to (x, y) (arrow tip) |
| xytext | Coordinates for text placement position. Default is None (text is placed at the xy position) |
| xycoords / textcoords | Coordinate system of xy / xytext: 'data', 'axes fraction', 'figure fraction', 'offset points', etc. |
| arrowprops | Arrow property dictionary, e.g., dict(arrowstyle='->', color='gray', lw=1.5) |
The core value of annotate is that xy and xytext can separately specify the coordinate point and the text position, and use an arrow to connect the two, which text() cannot do.
arrowprops Common Arrow Styles
| Style | Effect |
|---|---|
| '->' | Solid triangle arrow |
| '-' | No line |
| '<->' | Double-headed arrow |
| '-[widthB=...,lengthB=...]' | Custom rectangular arrow |
| 'fancy' | Elegant curved arrow |
| 'simple' | Simple straight arrow |
Usage Examples
Example 1: Basic Text Addition (text)
Example
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots(figsize=(8, 4), layout='constrained')
ax.plot(x, y, 'steelblue', linewidth=2)
# Add a text label at the peak
peak_idx = np.argmax(y)
ax.text(x[peak_idx], y[peak_idx] + 0.1,
f'Peak: ({x[peak_idx]:.2f}, {y[peak_idx]:.2f})',
fontsize=10, color='red',
ha='center', va='bottom',
fontweight='bold')
# Add text + background box at the valley
valley_idx = np.argmin(y)
ax.text(x[valley_idx], y[valley_idx] - 0.15,
f'Valley: ({x[valley_idx]:.2f}, {y[valley_idx]:.2f})',
fontsize=10, ha='center', va='top',
bbox=dict(boxstyle='round,pad=0.3',
facecolor='yellow', alpha=0.7))
ax.set_title('text() - Adding Text at Specific Coordinates')
ax.set_xlabel('x')
ax.set_ylabel('sin(x)')
ax.grid(True, alpha=0.3)
plt.show()
Example 2: Arrow Annotation (annotate)
Example
import numpy as np
x = np.linspace(0, 10, 50)
y = np.exp(-x/3) * np.sin(2 * x) # Damped oscillation
fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')
ax.plot(x, y, 'steelblue', linewidth=2, marker='o', markersize=4)
# Annotate the first peak (the arrow points from the text to the data point)
peak1_idx = np.argmax(y)
ax.annotate('1st Peak',
xy=(x[peak1_idx], y[peak1_idx]), # The point the arrow points to
xytext=(x[peak1_idx] + 1.5, y[peak1_idx] + 0.2), # Text position
arrowprops=dict(arrowstyle='->',
color='red', lw=1.5),
fontsize=11, color='red', fontweight='bold')
# Annotate the decay region
ax.annotate('Decay region',
xy=(.7, .3), xycoords='axes fraction', # Use axes coordinates
xytext=(0.5, 0.8), textcoords='axes fraction',
arrowprops=dict(arrowstyle='fancy',
color='green',
connectionstyle='arc3,rad=0.3'),
fontsize=11, color='green',
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
ax.set_title('annotate() - Annotations with Arrows')
ax.set_xlabel('Time (s)')
ax.set_ylabel('Amplitude')
ax.grid(True, alpha=0.3)
plt.show()
Example 3: Formula Annotation and Coordinate System
Example
import numpy as np
x = np.linspace(0, 4*np.pi, 200)
y1 = np.sin(x)
y2 = np.cos(x)
fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')
ax.plot(x, y1, 'blue', label='sin(x)')
ax.plot(x, y2, 'red', label='cos(x)')
# Annotate with a mathematical formula at a fixed position in the chart
ax.text(0.02, 0.95,
r'$f(x) = sin(x)$',
transform=ax.transAxes, # Use Axes relative coordinates (0-1)
fontsize=14, color='blue',
verticalalignment='top',
bbox=dict(boxstyle='round', facecolor='lightblue', alpha=0.5))
ax.text(0.02, 0.82,
r'$g(x) = cos(x)$',
transform=ax.transAxes,
fontsize=14, color='red',
verticalalignment='top',
bbox=dict(boxstyle='round', facecolor='lightcoral', alpha=0.5))
ax.set_title(r'Math Formula with LaTeX: $sum_{i=1}^{n} x_i$')
ax.set_xlabel('x (radians)')
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()
print("example: math annotation displayed")
FAQ
What is the difference between text and annotate?
text()Only places text at specified coordinates, suitable for adding labels or descriptions.
annotate()Can add an arrow connecting the text and the data point, suitable for precisely annotating key positions.
How to use mathematical formulas in text?
Use LaTeX syntax:r'$alpha + beta$'The r prefix indicates a raw string, and the content inside $...$ will be rendered as a mathematical formula.
Requires LaTeX to be installed on the system, or use Matplotlib's built-in mathtext renderer.
Other Extensions