基本标注
使用text()
会将文本放置在轴域的任意位置。 文本的一个常见用例是标注绘图的某些特征,而annotate()
方法提供辅助函数,使标注变得容易。 在标注中,有两个要考虑的点:由参数xy
表示的标注位置和xytext
的文本位置。 这两个参数都是(x, y)
元组。
import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) t = np.arange(0.0, 5.0, 0.01) s = np.cos(2*np.pi*t) line, = ax.plot(t, s, lw=2) ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5), arrowprops=dict(facecolor='black', shrink=0.05), ) ax.set_ylim(-2,2) plt.show(
在该示例中,xy
(箭头尖端)和xytext
位置(文本位置)都以数据坐标为单位。 有多种可以选择的其他坐标系 - 你可以使用xycoords
和textcoords
以及下列字符串之一(默认为data
)指定xy
和xytext
的坐标系。
| 参数 | 坐标系 |
| 'figure points'
| 距离图形左下角的点数量 |
| 'figure pixels'
| 距离图形左下角的像素数量 |
| 'figure fraction'
| 0,0 是图形左下角,1,1 是右上角 |
| 'axes points'
| 距离轴域左下角的点数量 |
| 'axes pixels'
| 距离轴域左下角的像素数量 |
| 'axes fraction'
| 0,0 是轴域左下角,1,1 是右上角 |
| 'data'
| 使用轴域数据坐标系 |
例如将文本以轴域小数坐标系来放置,我们可以:
ax.annotate('local max', xy=(3, 1), xycoords='data', xytext=(0.8, 0.95), textcoords='axes fraction', arrowprops=dict(facecolor='black', shrink=0.05), horizontalalignment='right', verticalalignment='top', )
对于物理坐标系(点或像素),原点是图形或轴的左下角。
或者,你可以通过在可选关键字参数arrowprops
中提供箭头属性字典来绘制从文本到注释点的箭头。
arrowprops 键 | 描述 |
---|---|
width | 箭头宽度,以点为单位 |
frac | 箭头头部所占据的比例 |
headwidth | 箭头的底部的宽度,以点为单位 |
shrink | 移动提示,并使其离注释点和文本一些距离 |
**kwargs | matplotlib.patches.Polygon 的任何键,例如facecolor |
在下面的示例中,xy
点是原始坐标(xycoords
默认为'data'
)。 对于极坐标轴,它在(theta, radius)
空间中。 此示例中的文本放置在图形小数坐标系中。 matplotlib.text.Text
关键字args
,例如horizontalalignment
,verticalalignment
和fontsize
,从annotate
传给Text
实例。
注释(包括花式箭头)的所有高上大的内容的更多信息,请参阅高级标注和pylab_examples示例代码:annotation_demo.py。
详细请看: