【问题标题】:How to add a text into a Rectangle?如何将文本添加到矩形中?
【发布时间】:2013-01-09 23:31:12
【问题描述】:

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

矩形是

的实例
    matplotlib.patches.Rectangle

我想在这些矩形中输入一个文本(实际上是一个数字),但我没有办法做到这一点。 matplotlib.text.Text 似乎允许插入由矩形包围的文本,但是我希望矩形处于精确的位置并具有精确的大小,我认为 text() 无法做到这一点。

【问题讨论】:

    标签: python matplotlib label rectangles


    【解决方案1】:

    我认为您需要使用轴对象的注释方法。

    您可以使用矩形的属性来了解它。这是一个玩具示例:

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

    【讨论】:

    • 感谢您的回答。您的技术有效,但要求矩形区域大于您输入的单词的宽度。在我的情况下,矩形真的很小(可以在原始帖子图像中看到),这是你的方法给出的:very small rectangle
    • 好的。因此,使用fontsize kwarg 调整annotate 方法中文本的​​大小并使用适当的字符串。我编辑了示例以包含指定的fontsize
    • 当然我已经考虑过了,很难根据矩形的大小调整字体大小..
    • 如果盒子需要在绘图之外,比如在 x 轴下方怎么办?
    猜你喜欢
    • 2016-12-14
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多