如何使紧紧的边框尊重无形的艺术家?

时间:2019-04-29 08:56:31

标签: matplotlib bounding-box

我想导出一个其边界框应该紧的图形,但要考虑一个看不见的艺术家。 (我想在情节的后续变体中公开这位艺术家,该变体应具有相同的边界框。)

我的解决方法是:

from matplotlib import pyplot as plt

plt.plot([0,1])
title = plt.title("my invisible title")
title.set_visible(False)
plt.savefig(
        "invisible_artist.png",
        bbox_inches="tight", pad_inches=0,
        bbox_extra_artists=[title],
        facecolor="grey", # just to visualise the bbox
    )

这将产生:

output of above script

为进行比较,下面是标题可见的输出,这是我在这种情况下的预期结果:

output with visible title

很明显,当标题变为不可见时,将不留任何空间,而在其他方向添加了额外的空间。

为什么会发生这种情况,如何获得所需的结果,即在两种情况下都具有相同的边界框?

2 个答案:

答案 0 :(得分:2)

对于严格的bbox计算,不考虑隐形艺术家。一些解决方法可能是使标题透明,

title.set_alpha(0)

或者使用空格作为标题

plt.title(" ")

更一般地说,您当然可以在 之前得到紧边框,使标题不可见,然后使标题不可见,最后将图形与以前存储的bbox一起保存。

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([0,1])
title = ax.set_title("my invisible title")

bbox = fig.get_tightbbox(fig.canvas.get_renderer())
title.set_visible(False)

plt.savefig(
        "invisible_artist.png",
        bbox_inches=bbox,
        facecolor="grey", # just to visualise the bbox
    )

plt.show()

Customizing android.widget.SearchView

缺点是pad_inches仅适用于bbox_inches="tight"。因此,要为这种手动指定的bbox达到pad_inches的效果,就需要操纵Bbox本身。

答案 1 :(得分:0)

只需将标题的颜色指定为与facecolor相同,即您的情况下为'grey'。现在,您不需要title.set_visible(False)。我通过使用变量col指定颜色来使其更通用

from matplotlib import pyplot as plt

col = 'grey'
plt.plot([0,1])
title = plt.title("my invisible title", color=col)
plt.savefig(
        "invisible_artist.png",
        bbox_inches="tight", pad_inches=0,
        bbox_extra_artists=[title],
        facecolor=col, # just to visualise the bbox
    )

enter image description here

相关问题