matplotlib如何在画矩形时增加文字说明
时间: 2023-10-27 14:12:56 浏览: 40
您可以使用Matplotlib中的text()函数在矩形旁边添加文字说明。具体步骤如下:
1. 绘制矩形,使用Matplotlib中的Rectangle()函数创建矩形对象。例如:
```python
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
rect = Rectangle((0.2, 0.2), 0.3, 0.4, fill=False)
plt.gca().add_patch(rect)
```
这将创建一个左上角坐标为(0.2, 0.2),宽度为0.3,高度为0.4的矩形。
2. 添加文字说明,使用Matplotlib中的text()函数。例如:
```python
plt.text(0.45, 0.4, "This is a rectangle", fontsize=12)
```
这将在矩形右侧添加文字说明,文字内容为"This is a rectangle",字体大小为12。
完整代码示例:
```python
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
rect = Rectangle((0.2, 0.2), 0.3, 0.4, fill=False)
plt.gca().add_patch(rect)
plt.text(0.45, 0.4, "This is a rectangle", fontsize=12)
plt.show()
```