我有一段代码,在一张图片上画了几百个小矩形。
矩形的实例是
matplotlib.patches.Rectangle
Matplotlib.text.Text似乎允许插入被矩形包围的文本,但是我希望矩形在一个精确的位置,并有一个精确的大小,我不认为这可以用text()来实现。
我想你需要使用 axes 对象的 annotate 方法。
你可以使用矩形的属性来聪明地处理它。这里有一个玩具的例子。
import matplotlib.pyplot as plt
import matplotlib.patches as mpatch
fig, ax = plt.subplots()
rectangles = {'skinny' : mpatch.Rectangle((2,2), 8, 2),
'square' : mpatch.Rectangle((4,6), 6, 6)}
for r in rectangles:
ax.add_artist(rectangles[r])
rx, ry = rectangles[r].get_xy()
cx = rx + rectangles[r].get_width()/2.0
cy = ry + rectangles[r].get_height()/2.0
ax.annotate(r, (cx, cy), color='w', weight='bold',
fontsize=6, ha='center', va='center')
ax.set_xlim((0, 15))
ax.set_ylim((0, 15))
ax.set_aspect('equal')
plt.show()