现在位置: 首页 > Matplotlib 教程 > 正文

Matplotlib text() / annotate() 函数


Matplotlib 参考文档 Matplotlib 参考文档

text() 在图表指定坐标处添加文本,annotate() 添加带箭头的标注,可精确指向数据点。

函数定义

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)

参数说明

text() 参数

参数说明
x, y文本位置坐标
s要显示的文本字符串
fontsize字体大小
color文本颜色
ha / horizontalalignment水平对齐:'center'、'right'、'left'
va / verticalalignment垂直对齐:'center'、'top'、'bottom'、'baseline'
rotation旋转角度(度数)
fontweight字重:'normal'、'bold'、'light'
bbox文本背景框属性,如 dict(facecolor='yellow', alpha=0.5)

annotate() 特有参数

参数说明
text标注文本内容
xy被指向的目标点坐标 (x, y)(箭头尖端)
xytext文本放置位置坐标。默认 None(文本放在 xy 位置)
xycoords / textcoordsxy / xytext 的坐标系统:'data'、'axes fraction'、'figure fraction'、'offset points' 等
arrowprops箭头属性字典,如 dict(arrowstyle='->', color='gray', lw=1.5)

annotate 的核心价值在于 xy 和 xytext 可以分别指定坐标点和文本位置,并用箭头连接两者,这是 text() 做不到的。

arrowprops 常用箭形样式

样式效果
'->'实心三角箭头
'-'无线条
'<->'双向箭头
'-[widthB=...,lengthB=...]'自定义矩形箭头
'fancy'优雅弯曲箭头
'simple'简单直线箭头

使用示例

示例 1:基本文本添加 (text)

实例

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)

# 在峰值处添加文本标记
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')

# 在谷值处添加文本 + 背景框
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()

示例 2:箭头标注 (annotate)

实例

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 50)
y = np.exp(-x/3) * np.sin(2 * x)  # 阻尼振动

fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')
ax.plot(x, y, 'steelblue', linewidth=2, marker='o', markersize=4)

# 标注第一个峰值(箭头从文本指向数据点)
peak1_idx = np.argmax(y)
ax.annotate('1st Peak',
            xy=(x[peak1_idx], y[peak1_idx]),          # 箭头指向的点
            xytext=(x[peak1_idx] + 1.5, y[peak1_idx] + 0.2),  # 文本位置
            arrowprops=dict(arrowstyle='-&gt;',
                            color='red', lw=1.5),
            fontsize=11, color='red', fontweight='bold')

# 标注衰减区域
ax.annotate('Decay region',
            xy=(.7, .3), xycoords='axes fraction',     # 使用 axes 坐标
            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()

示例 3:公式标注与坐标系统

实例

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)')

# 在图表固定位置用数学公式标注
ax.text(0.02, 0.95,
        r'$f(x) = sin(x)$',
        transform=ax.transAxes,    # 使用 Axes 相对坐标 (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("runoob: math annotation displayed")

常见问题

text 和 annotate 有什么区别?

text() 仅在指定坐标放置文本,适合添加标签或说明。

annotate() 可以添加箭头连接文本和数据点,适合精确标注关键位置。

如何在文本中使用数学公式?

使用 LaTeX 语法:r'$alpha + beta$'。r 前缀表示原始字符串,$...$ 内的内容会被渲染为数学公式。

需要系统安装 LaTeX 或使用 Matplotlib 内置的 mathtext 渲染器。


Matplotlib 参考文档 Matplotlib 参考文档