plt.text的作用
时间: 2023-10-30 13:03:20 浏览: 54
plt.text()函数用于在matplotlib图形中添加文字说明。它可以在指定的坐标位置(x, y)上插入字符串(string),并且可以设置字体大小(fontsize)、垂直对齐方式(verticalalignment)和水平对齐方式(horizontalalignment)。
该函数的语法格式为:plt.text(x, y, s, fontsize, verticalalignment, horizontalalignment, rotation, kwargs) 。其中,(x, y)参数表示句子头的坐标。通过指定不同的(x, y)坐标,可以在图形中的不同位置插入文字。
以下是一个示例,展示了如何使用plt.text()函数在matplotlib图形中添加文字说明:
```python
import matplotlib.pyplot as plt
fig = plt.figure()
plt.axis([0, 10, 0, 10])
# 设置要插入的字符串
t = "This is a really long string that I'd rather have wrapped so that it" \
" doesn't go outside of the figure, but if it's long enough it will go" \
" off the top or bottom!"
# 在指定坐标位置插入文字,并设置水平对齐方式和旋转角度
plt.text(6, 5, t, ha='left', rotation=15, wrap=True)
plt.text(6, 5, t, ha='left', rotation=-15, wrap=True)
plt.text(6, 5, t, ha='left', rotation=-50, wrap=True)
plt.show()
```
在上述示例中,我们先创建了一个图形对象fig,并通过plt.axis()函数设置了图形的坐标轴范围。然后,我们定义了一个要插入的长字符串t。接下来,使用plt.text()函数在图形的指定坐标位置(6, 5)插入了t字符串,并通过设置ha参数来指定水平对齐方式。还可以通过设置rotation参数来旋转文本的角度,以及通过wrap参数来指定是否自动换行。
最后,使用plt.show()函数显示出图形,从而展示了plt.text()函数的效果。