Matplotlib text() / annotate() Function


Matplotlib 参考文档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

ParameterDescription
x, yText position coordinates
sThe text string to display
fontsizeFont size
colorText color
ha / horizontalalignmentHorizontal alignment: 'center', 'right', 'left'
va / verticalalignmentVertical alignment: 'center', 'top', 'bottom', 'baseline'
rotationRotation angle (degrees)
fontweightFont weight: 'normal', 'bold', 'light'
bboxText background box properties, e.g., dict(facecolor='yellow', alpha=0.5)

annotate() Specific Parameters

ParameterDescription
textAnnotation text content
xyCoordinates of the target point being pointed to (x, y) (arrow tip)
xytextCoordinates for text placement position. Default is None (text is placed at the xy position)
xycoords / textcoordsCoordinate system of xy / xytext: 'data', 'axes fraction', 'figure fraction', 'offset points', etc.
arrowpropsArrow 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

StyleEffect
'->'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 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 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 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 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='-&gt;',
                            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 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', 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.


Matplotlib 参考文档Matplotlib Reference Documentation

Other Extensions