我正在尝试创建具有相同像素大小的 imshow 子图,但不自动缩放图形高度,但我无法弄清楚如何实现。
理想情况下,我正在寻找类似于第二张图片的图,没有额外的空白(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
表示图之间的空间与其宽度一样大。
结果是子图的宽度大小相同的图形。
关于python - 如何创建具有相同像素大小的 python imshow 子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53346246/