如何让紧凑的边界框尊重隐形艺术家?
How to make tight bounding boxes respect an invisible artist?
我想导出一个图形,其边界框应该很紧,但考虑到一个看不见的艺术家。
(我想在后来的情节变体中揭开那个艺术家的面纱,它应该有相同的边界框。)
我的做法是:
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
)
这会产生:
为了比较,这里是标题可见的输出,这是我在这种情况下所期望的:
显然,当标题不可见时,没有为它留下space,而在其他方向添加额外的space。
为什么会发生这种情况,我怎样才能达到预期的结果,即在两种情况下具有相同的边界框?
只需将标题的颜色指定为与 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
)
严格的 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()
缺点是 pad_inches
仅适用于 bbox_inches="tight"
。因此,要为这种手动指定的 bbox 实现 pad_inches
的效果,需要操纵 Bbox
本身。
我想导出一个图形,其边界框应该很紧,但考虑到一个看不见的艺术家。 (我想在后来的情节变体中揭开那个艺术家的面纱,它应该有相同的边界框。)
我的做法是:
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
)
这会产生:
为了比较,这里是标题可见的输出,这是我在这种情况下所期望的:
显然,当标题不可见时,没有为它留下space,而在其他方向添加额外的space。
为什么会发生这种情况,我怎样才能达到预期的结果,即在两种情况下具有相同的边界框?
只需将标题的颜色指定为与 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
)
严格的 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()
缺点是 pad_inches
仅适用于 bbox_inches="tight"
。因此,要为这种手动指定的 bbox 实现 pad_inches
的效果,需要操纵 Bbox
本身。