如何使子图的大小相等?

Posted

技术标签:

【中文标题】如何使子图的大小相等?【英文标题】:How to make the size of subplot equally? 【发布时间】:2019-07-31 03:10:14 【问题描述】:

我正在使用 matplotlib 和 GridSpec 在 3x3 子图中绘制 9 个图像。

    fig = plt.figure(figsize=(30,40))
    fig.patch.set_facecolor('white')
    gs1 = gridspec.GridSpec(3,3)
    gs1.update(wspace=0.05, hspace=0.05)
    ax1 = plt.subplot(gs1[0])
    ax2 = plt.subplot(gs1[1])
    ax3 = plt.subplot(gs1[2])
    ax4 = plt.subplot(gs1[3])
    ax5 = plt.subplot(gs1[4])
    ax6 = plt.subplot(gs1[5])
    ax7 = plt.subplot(gs1[6])
    ax8 = plt.subplot(gs1[7])
    ax9 = plt.subplot(gs1[8])
    ax1.imshow(img1,cmap='gray')
    ax2.imshow(img2,cmap='gray')
    ...
    ax9.imshow(img9,cmap='gray')

但是,每行的图像大小不同。例如,第一行图片大小为 256x256,第二行图片大小为 200x200,第三行图片大小为 128x128

我想在子图中绘制相同大小的图像。我应该如何在 python 中使用它?谢谢

这是 4x3 子图的示例

【问题讨论】:

看看这个链接对你有没有帮助:***.com/questions/13714454/… 【参考方案1】:

不要使用matplotlib.gridspec,而是使用figure.add_subplot,如下面的可运行代码所示。但是,在做一些绘图时,你需要set_autoscale_on(False) 来抑制它的大小调整行为。

import numpy as np
import matplotlib.pyplot as plt

# a function that creates image array for `imshow()`
def make_img(h):
    return np.random.randint(16, size=(h,h)) 

fig = plt.figure(figsize=(8, 12))
columns = 3
rows = 4
axs = []

for i in range(columns*rows):
    axs.append( fig.add_subplot(rows, columns, i+1) )

    # axs[-1] is the new axes, write its title as `axs[number]`
    axs[-1].set_title("axs[%d]" % (i))

    # plot raster image on this axes
    plt.imshow(make_img(i+1), cmap='viridis', alpha=(i+1.)/(rows*columns))

    # maniputate axs[-1] here, plot something on it
    axs[-1].set_autoscale_on(False)   # suppress auto sizing
    axs[-1].plot(np.random.randint(2*(i+1), size=(i+1)), color="red", linewidth=2.5)


fig.subplots_adjust(wspace=0.3, hspace=0.4)
plt.show()

结果图:

【讨论】:

【参考方案2】:

我想您想以不同尺寸显示图像,以便不同图像的所有像素大小相同。

这通常很难,但是对于子图网格的一行(或列)中的所有图像都具有相同大小的情况,它变得容易了。想法可以是使用 gridspec 的 height_ratios(或 width_ratios 在列的情况下)参数并将其设置为图像的像素高度(宽度)。

import matplotlib.pyplot as plt
import numpy as np

images = [np.random.rand(r,r) for r in [25,20,12] for _ in range(3)]


r = [im.shape[0] for im in images[::3]]
fig, axes = plt.subplots(3,3, gridspec_kw=dict(height_ratios=r, hspace=0.3))

for ax, im in zip(axes.flat, images):
    ax.imshow(im)


plt.show()

【讨论】:

对不起。我有 9 张不同尺寸的图片。如何将其绘制到 3x3 子图,以使子图的大小必须相同。误会请见谅

以上是关于如何使子图的大小相等?的主要内容,如果未能解决你的问题,请参考以下文章

在 matplotlib 中设置子图的大小

在带有子图的 geopandas 图中添加图例会改变图的大小

更改 matplotlib 子图的大小

matlab subplot 如何自定义各子图的大小和位置

在 matplotlib 中调整单个子图的大小

python中不均匀的子图