如何将文本添加到矩形中? [英] How to add a text into a Rectangle?

查看:146
本文介绍了如何将文本添加到矩形中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码,可以在图像上方绘制数百个小矩形:

I have a code that draws hundreds of small rectangles on top of an image :

矩形是

    matplotlib.patches.Rectangle

我想在这些矩形中放入一个文本(实际上是一个数字),但没有找到一种方法. matplotlib.text.Text似乎允许插入由矩形包围的文本,但是我希望矩形位于精确的位置并具有精确的大小,我不认为可以使用text()做到这一点.

I'd like to put a text (actually a number) into these rectangles, I don't see a way to do that. matplotlib.text.Text seems to allow one to insert text surrounded by a rectangle however I want the rectangle to be at a precise position and have a precise size and I don't think that can be done with text().

推荐答案

我认为您需要使用axes对象的annotate方法.

I think you need to use the annotate method of your axes object.

您可以使用矩形的属性来提高其智能性.这是一个玩具示例:

You can use properties of the rectangle to be smart about it. Here's a toy example:

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()

这篇关于如何将文本添加到矩形中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆