如何制作紧密的边框尊重隐形艺术家?

问题描述 投票:1回答:2

我想导出一个数字,其边界框应该是紧的,但要考虑一个看不见的艺术家。 (我想在后来的情节变体中揭开该艺术家的作用,它将具有相同的边界框。)

我的方法是:

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

显然,当标题不可见时,没有空间留给它,而在其他方向添加额外的空间。

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

matplotlib bounding-box
2个回答
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()

image

缺点是pad_inches只适用于bbox_inches="tight"。因此,为了实现pad_inches对这种手动指定的bbox的影响,需要操纵Bbox本身。


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

© www.soinside.com 2019 - 2024. All rights reserved.