如何在一个矩形中添加文字?

问题描述 投票:21回答:1

我有一段代码,在一张图片上画了几百个小矩形。

example

矩形的实例是

    matplotlib.patches.Rectangle

Matplotlib.text.Text似乎允许插入被矩形包围的文本,但是我希望矩形在一个精确的位置,并有一个精确的大小,我不认为这可以用text()来实现。

python matplotlib label rectangles
1个回答
31
投票

我想你需要使用 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()

annotated rectangles

© www.soinside.com 2019 - 2024. All rights reserved.