如何在矩形中添加文本?

31 投票
2 回答
29683 浏览
提问于 2025-04-17 13:42

我有一段代码,可以在一张图片上画出数百个小矩形:

example

这些矩形是

    matplotlib.patches.Rectangle

我想在这些矩形里放一些文字(其实是数字),但我找不到办法做到这一点。虽然matplotlib.text.Text似乎可以让你在一个矩形里插入文字,但我希望矩形的位置和大小都是精确的,而我觉得用text()是做不到的。

2 个回答

1

这是一个示例。

import matplotlib.pyplot as plt

left, width = .25, .25
bottom, height = .25, .25
right = left + width
top = bottom + height
fig, ax = plt.subplots(figsize=(10, 10),sharex=True, sharey=True)

fig.patches.extend([plt.Rectangle((left, bottom), width, height,
                                      facecolor='none',
                                      edgecolor='red',
                                      #fill=True, 
                                      #color='black', 
                                      #alpha=0.5, 
                                      #zorder=1000,
                                      lw=5, 
                                      transform=fig.transFigure, figure=fig)])

fig.text(0.5*(left+right), 0.5*(bottom+top), 'Your text',
    horizontalalignment='center',
    verticalalignment='center',
    fontsize=20, color='black',
    transform=fig.transFigure)

在这里输入图片描述

47

我觉得你需要使用你坐标轴对象的 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()

带注释的矩形

撰写回答