首页 > 解决方案 > How to create python imshow subplots with same pixel size

问题描述

I'm trying to create imshow subplots with the same pixel size without having the figure height automatically scaled, but I haven't been able to figure out how.

Ideally, I'm looking for a plot similar to the second picture, without the extra white space (ylim going from -0.5 to 4.5) and maybe centered vertically. My pictures will always have the same width, so maybe if I could fix the subplot width instead of the height that would help. Does anyone have any ideas?

close('all')
f,ax=subplots(1,2)
ax[0].imshow(random.rand(30,4),interpolation='nearest')
ax[1].imshow(random.rand(4,4),interpolation='nearest')
tight_layout()

f,ax=subplots(1,2)
ax[0].imshow(random.rand(30,4),interpolation='nearest')
ax[1].imshow(random.rand(4,4),interpolation='nearest')
ax[1].set_ylim((29.5,-0.5))
tight_layout()

Plot without ylim adjustment:

Plot without ylim adjustment

Plot with ylim adjustment:

Plot with ylim adjustment

标签: pythonmatplotlibimshow

解决方案


原则上,您可以使图形尺寸在宽度上足够小,以限制子图的宽度。例如figsize=(2,7)会在这里工作。

对于自动化解决方案,您可以调整子图参数,以便左右边距限制子图宽度。这显示在下面的代码中。它假设有一行子图,并且所有图像在水平方向上具有相同的像素数。

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1,2)
im1 = ax[0].imshow(np.random.rand(30,4))
im2 = ax[1].imshow(np.random.rand(4,4))


def adjustw(images, wspace="auto"):
    fig = images[0].axes.figure
    if wspace=="auto":
        wspace = fig.subplotpars.wspace
    top = fig.subplotpars.top
    bottom = fig.subplotpars.bottom
    shapes = np.array([im.get_array().shape for im in images])
    w,h = fig.get_size_inches()
    imw = (top-bottom)*h/shapes[:,0].max()*shapes[0,1] #inch
    n = len(shapes)
    left = -((n+(n-1)*wspace)*imw/w - 1)/2.
    right = 1.-left
    fig.subplots_adjust(left=left, right=right, wspace=wspace)

adjustw([im1, im2], wspace=1)

plt.show()

如果您需要使用tight_layout(),请在调用该函数之前执行此操作。此外,您肯定需要在此处设置唯一的自由参数,wspace而不是"auto". wspace=1意味着图之间的空间与它们的宽度一样多。

结果是子图的宽度相同的图形。

在此处输入图像描述


推荐阅读