调整matplotlib注释框内的填充

2024-10-02 14:16:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用annotate方法对Axes对象添加一个带文本的箭头到绘图。例如:

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

这很好,但我想减少注释框内部的填充。基本上,我想把文本框“挤压”得更紧。有什么方法可以通过arrowpropsbbox_propskwargs来实现这一点吗?

我正在寻找像borderpad这样的东西,可以在传说中找到,类似于讨论的on this answer


Tags: 对象方法文本绘图helloworlddata箭头
1条回答
网友
1楼 · 发布于 2024-10-02 14:16:32

是的,但是您需要切换到稍微不同的方式来指定框。“basic”框不支持它,因此需要让annotate与文本对象关联FancyBboxPatch。(同样的语法对于一个“花哨的”框也适用于放在ax.text上的文本,不管它值多少钱。)


另外,在我们进一步讨论之前,在当前版本的matplotlib(1.4.3)中有几个相当棘手的错误会影响到这一点。(例如https://github.com/matplotlib/matplotlib/issues/4139https://github.com/matplotlib/matplotlib/issues/4140

如果你看到这样的事情: enter image description here

而不是这个: enter image description here

在问题解决之前,可以考虑降级到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()

enter image description here

要更改填充,您需要使用bboxkwarg来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()

enter image description here

默认填充为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()

enter image description here

或者可以通过放入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()

enter image description here

相关问题 更多 >

    热门问题