如何在 Matplotlib 中向一个长方形中添加文本?


要在 matplotlib 中向一个长方形中添加文本,我们可以使用 annotate() 方法在长方形的中心位置添加一个标签。

步骤

  • 使用 figure() 方法创建一个图像或激活一个现有的图像。

  • 在当前轴中添加一个子图布局。

  • 要在绘图中添加一个长方形,使用Rectangle() 类获取长方形对象。

  • 在绘图上添加一个长方形块。

  • 要在长方形中添加文本标签,我们可以获得长方形的中心值,即 cx 和 cy。

  • 使用annotate() 方法在长方形上放置文本。

  • 限制 x 和 y 轴以获得一个可见的长方形。

  • 使用show() 方法显示图像。

示例

from matplotlib import pyplot as plt, patches
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot(111)
rectangle = patches.Rectangle((0, 0), 3, 3, edgecolor='orange',
facecolor="green", linewidth=7)
ax.add_patch(rectangle)
rx, ry = rectangle.get_xy()
cx = rx + rectangle.get_width()/2.0
cy = ry + rectangle.get_height()/2.0
ax.annotate("Rectangle", (cx, cy), color='black', weight='bold', fontsize=10, ha='center', va='center')
plt.xlim([-5, 5])
plt.ylim([-5, 5])
plt.show()

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

更新于: 2021 年 5 月 12 日

6K+ 浏览量

开启你的 职业

完成课程获得认证

开始
广告