调整 matplotlib 注释框内的填充

Adjust padding inside matplotlib annotation box

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

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

这很好用,但我想减少注释框内部的填充。本质上,我想让文本周围的方框 'squeeze' 更紧。有什么办法可以通过 arrowpropsbbox_props kwargs 做到这一点?

我正在寻找像 borderpad 这样的东西,它在传说中可用,类似于 on this answer 所讨论的内容。

是的,但是您需要切换到一种稍微不同的指定方框的方式。 "basic" 框不支持它,因此您需要让 annotate 创建一个与文本对象关联的 FancyBboxPatch。 ("fancy" 框的相同语法也适用于 ax.text 放置的文本,因为它的价值。)


此外,在我们深入探讨之前,当前版本的 matplotlib (1.4.3) 中有几个相当棘手的错误会影响这一点。 (例如 https://github.com/matplotlib/matplotlib/issues/4139 and https://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。 (如果我没记错的话,单位是文本范围 height/width 的分数。)如果您想增加它,请使用 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()