如何创建 python imshow 具有相同像素大小的子图
How to create python imshow subplots with same pixel size
我正在尝试创建具有相同像素大小的 imshow 子图而不自动缩放图形高度,但我一直无法弄清楚如何。
理想情况下,我正在寻找类似于第二张图片的图,没有额外的白色 space(ylim 从 -0.5 到 4.5)并且可能垂直居中。我的图片将始终具有相同的宽度,所以也许如果我可以修复子图的宽度而不是高度会有帮助。有人有什么想法吗?
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()
没有 ylim 调整的绘图:
带有 ylim 调整的绘图:
原则上你可以让图形的宽度足够小,这样它就可以限制子图的宽度。例如。 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
表示图之间的 space 与它们的宽度一样多。
结果是一个图形,其中子图的宽度大小相同。
我正在尝试创建具有相同像素大小的 imshow 子图而不自动缩放图形高度,但我一直无法弄清楚如何。
理想情况下,我正在寻找类似于第二张图片的图,没有额外的白色 space(ylim 从 -0.5 到 4.5)并且可能垂直居中。我的图片将始终具有相同的宽度,所以也许如果我可以修复子图的宽度而不是高度会有帮助。有人有什么想法吗?
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()
没有 ylim 调整的绘图:
带有 ylim 调整的绘图:
原则上你可以让图形的宽度足够小,这样它就可以限制子图的宽度。例如。 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
表示图之间的 space 与它们的宽度一样多。
结果是一个图形,其中子图的宽度大小相同。