【问题标题】:Matplotlib savefig with tight layout and suptitle generates extra space between title and images具有紧凑布局和字幕的 Matplotlib savefig 在标题和图像之间产生额外的空间
【发布时间】:2022-01-01 20:51:16
【问题描述】:

在网上,我发现了类似的问题,但我还没有找到解决方案。

以下代码:

import numpy as np
import matplotlib.pyplot as plt

imgs = [np.random.randint(0, 256, size=(512, 512, 3)) for _ in range(3)]

_, axes = plt.subplots(1, 3)
title = plt.suptitle("My title")
axes[0].imshow(imgs[0])
axes[0].set_axis_off()
axes[1].imshow(imgs[1])
axes[1].set_axis_off()
axes[2].imshow(imgs[2])
axes[2].set_axis_off()
plt.savefig("myfig.png", bbox_inches="tight",
            bbox_extra_artists=[title])
plt.close()

给我以下输出:

如何去除标题和图片之间的多余空格?

【问题讨论】:

    标签: python-3.x matplotlib spacing


    【解决方案1】:

    这里的问题是您的轴具有固定的纵横比,并且您的绘图比需要的高。您的绘图上方和下方都会有空白区域,您可以尝试使用box_inches='tight' 消除这些空白区域。

    Matplotlib 中一个直接的解决方案是使图形的纵横比接近轴的纵横比:

    fig, axs = plt.subplots(1, 3, figsize(6, 2)
    

    接近了,之后就可以玩结果了。

    第二种方法是不使用通用的suptitle,而是直接使用ax.text,并使用轴的transAxes属性使x和y在轴的分数中:

    axes[1].text(0.5, 1.02, 'Boo!!!!!!', transform=axes[1].transAxes, ha='center')
    

    【讨论】:

      猜你喜欢
      • 2020-08-25
      • 2018-12-14
      • 1970-01-01
      • 2017-09-25
      • 1970-01-01
      • 2021-01-28
      • 1970-01-01
      • 2016-10-24
      • 1970-01-01
      相关资源
      最近更新 更多