【问题标题】:Adjust padding inside matplotlib annotation box调整 matplotlib 注释框内的填充
【发布时间】:2015-03-18 10:04:57
【问题描述】:

我在Axes 对象上使用annotate 方法将带有文本的箭头添加到绘图中。例如:

ax.annotate('hello world,
            xy=(1, 1),
            xycoords='data',
            textcoords='data',
            fontsize=12,
            backgroundcolor='w',
            arrowprops=dict(arrowstyle="->",
                            connectionstyle="arc3")

这很好用,但我想减少注释框内部的填充。本质上,我想让框在文本周围“挤压”得更紧。有没有办法通过arrowpropsbbox_props kwargs 做到这一点?

我正在寻找类似 @​​987654327@ 的东西,可以在图例中找到,类似于讨论的 on this answer

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    是的,但您需要切换到稍微不同的方式来指定框。 “基本”框不支持它,因此您需要让annotate 使FancyBboxPatch 与文本对象关联。 (“花式”框的相同语法也适用于带有 ax.text 的文本,不管它的价值。)


    此外,在我们走得更远之前,在当前版本的 matplotlib (1.4.3) 中有几个相当棘手的错误会影响这一点。 (例如https://github.com/matplotlib/matplotlib/issues/4139https://github.com/matplotlib/matplotlib/issues/4140

    如果您看到这样的情况:

    取而代之的是:

    在问题得到解决之前,您可以考虑降级到 matplotlib 1.4.2。


    让我们以您的示例为起点。我已将背景颜色更改为红色并将其放在图形的中心以使其更易于查看。我也打算离开箭头(避免上面的错误),只使用ax.text 而不是annotate

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    a = ax.text(0.5, 0.5, 'hello world',
                fontsize=12,
                backgroundcolor='red')
    
    plt.show()
    

    为了能够更改填充,您需要使用 bbox kwarg 到 text(或 annotate)。这使得文本使用FancyBboxPatch,它支持填充(以及其他一些东西)。

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    a = ax.text(0.5, 0.5, 'hello world', fontsize=12,
                bbox=dict(boxstyle='square', fc='red', ec='none'))
    
    plt.show()
    

    默认填充是pad=0.3。 (如果我没记错的话,单位是文本范围的高度/宽度的分数。)如果您想增加它,请使用boxstyle='square,pad=<something_larger>'

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    a = ax.text(0.5, 0.5, 'hello world', fontsize=12,
                bbox=dict(boxstyle='square,pad=1', fc='red', ec='none'))
    
    plt.show()
    

    或者您可以通过输入0 或负数来进一步缩小它:

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    a = ax.text(0.5, 0.5, 'hello world', fontsize=12,
                bbox=dict(boxstyle='square,pad=-0.3', fc='red', ec='none'))
    
    plt.show()
    

    【讨论】:

    • 感谢您的详细描述。我最终使用了annotate,但使用您建议的pad 参数调用set_bbox,并且效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多