调整matplotlib注释框内的填充

时间:2015-03-18 10:04:57

标签: python matplotlib

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

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

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

执行此操作

我正在寻找像borderpad这样的传说,类似于所讨论的on this answer

1 个答案:

答案 0 :(得分:6)

是的,但您需要切换到指定框的略有不同的方式。 “基本”框不支持它,因此您需要让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

为了能够更改填充,您需要使用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()

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