调整matplotlib注释框内的填充

dur*_*2.0 1 python matplotlib

我正在对象annotate上使用该方法Axes向绘图添加带有文本的箭头.例如:

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

这很好,但我想减少注释框内部的填充.从本质上讲,我想让文章围绕文本"挤压".有没有办法通过arrowpropsbbox_propskwargs 这样做?

我正在寻找像borderpad传说中那样的东西,类似于在这个答案中讨论的东西.

Joe*_*ton 6

是的,但您需要切换到指定框的略有不同的方式."基本"框不支持它,因此您需要与文本对象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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

为了能够更改填充,您需要使用bboxkwarg text(或annotate).这使得文本使用a 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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

默认填充是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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

或者您可以通过输入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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述