Skip to main content
 首页 » 编程设计

python之调整 matplotlib 注释框内的填充

2025年05月04日16虾米姐

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

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

这很好用,但我想减少注释框内部的填充。本质上,我想让文本框“挤压”得更紧。有什么办法可以通过 arrowprops 或 bbox_props kwargs 做到这一点?

我正在寻找像 borderpad 这样的东西,它在图例上可用,类似于讨论的内容 on this answer .

请您参考如下方法:

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


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