Matplotlib text() / annotate() Function
Source: https://example.com/matplotlib/matplotlib-ref-text.html
Matplotlib Reference Documentation
text() adds text at specified coordinates on the chart, annotate() adds annotations with arrows that 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 | 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 (in 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 where text is placed. Default None (text placed at xy position) |
| xycoords / textcoords | Coordinate system for xy / xytext: 'data', 'axes fraction', 'figure fraction', 'offset points', etc. |
| arrowprops | Arrow properties 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 text position, and connect them with an arrow, which text() cannot do.
Common arrowprops Arrow Styles
| Style | Effect |
|---|---|
| -> | Solid triangular arrow |
| - | No line |
| <-> | Bidirectional arrow |
| -[widthB=...,lengthB=...] | Custom rectangular arrow |
| fancy | Elegant curved arrow |
| simple | Simple straight arrow |
Usage Examples
Example 1: Basic Text Addition (text)
Instance
import matplotlib.pyplot as plt
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 text marker at peak
peak_idx = np.argmax(y)
ax.text(x, y + 0.1,
f'Peak: ({x:.2f}, {y:.2f})',
fontsize=10, color='red',
ha='center', va='bottom',
fontweight='bold')
# Add text + background box at valley
valley_idx = np.argmin(y)
ax.text(x, y - 0.15,
f'Valley: ({x:.2f}, {y:.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)
Instance
import matplotlib.pyplot as plt
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 first peak (arrow from text points to data point)
peak1_idx = np.argmax(y)
ax.annotate('1st Peak',
xy=(x, y),# Point being pointed to by arrow
xytext=(x + 1.5, y + 0.2),# Text position
arrowprops=dict(arrowstyle='->',
color='red', lw=1.5),
fontsize=11, color='red', fontweight='bold')
# Annotate 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
Instance
import matplotlib.pyplot as plt 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',
YouTip