python - 如何创建具有相同像素大小的 python imshow 子图

标签 python matplotlib imshow

我正在尝试创建具有相同像素大小的 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 调整的绘图:

Plot without ylim adjustment

使用 ylim 调整进行绘图:

Plot with ylim adjustment

最佳答案

原则上,您可以使图形尺寸的宽度足够小,从而限制子图的宽度。例如。 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 表示图之间的空间与其宽度一样大。

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

enter image description here

关于python - 如何创建具有相同像素大小的 python imshow 子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53346246/

相关文章:

列表语法的Python列表

python - 解析包含纳秒的日期时间字符串

python - 使用 Anaconda+Sublime 显示 pyplot Windows

python - 使用 plt 在热图上绘制梯度箭头

python - 更改我正在遍历的列表时的意外行为

python - 将 Python 项目及其依赖项打包到另一台没有互联网和不同操作系统的机器上

python - 尝试在networkx中绘制不可见节点,但得到黑色节点

python - 从加权边列表创建有向加权网络图

python - 我想在colab中使用imshow(),但是它不起作用

python - 为什么当我切换随机变量 Z(X, Y) 的 X 和 Y 时,线性回归是错误的?