如何在 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()

輸出

更新於: 2021 年 5 月 12 日

6K+ 瀏覽量

開啟你的 職業

完成課程獲得認證

開始
廣告