【问题标题】:How to make tight bounding boxes respect an invisible artist?如何让紧密的边界框尊重隐形艺术家?
【发布时间】:2019-04-29 08:56:30
【问题描述】:

我想导出一个边界框应该很紧的图形,但要考虑一个不可见的艺术家。 (我想在稍后的情节变体中揭开该艺术家的面纱,该变体应具有相同的边界框。)

我的做法是:

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
    )

这会产生:

为了比较,这里是标题可见的输出,这是我在这种情况下所期望的:

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

为什么会发生这种情况,我怎样才能达到预期的结果,即在两种情况下都有相同的边界框?

【问题讨论】:

    标签: matplotlib bounding-box


    【解决方案1】:

    在严格的 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

    【讨论】:

      【解决方案2】:

      只需将标题的颜色指定为与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
          )
      

      【讨论】:

      • 感谢您的回答,但我认为这充其量只是临时解决方法。此外,它还存在一些问题,例如无法转换为更复杂的艺术家(例如传说)和不均匀的背景,以及增加了跟踪该颜色的必要性。
      • @Wrzlprmft:我的目的是解决您提出的问题,但不提供一般解决方案。这确实是您所要求的解决方法。关于跟踪颜色,无论如何您都明确指定了 facecolor。在这种情况下,您可以使用变量 col='grey',然后在两个命令中都使用它。
      猜你喜欢
      • 2023-02-25
      • 2014-06-17
      • 2012-05-16
      • 2015-04-12
      • 1970-01-01
      • 2012-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多