python - 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 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
意味着图之间的空间与它们的宽度一样多。
结果是子图的宽度相同的图形。
推荐阅读
- google-chrome - 如何使用 webdriver 解析 window.chrome.runtime
- apache-kafka - 卡夫卡主题——我应该多点还是少点?
- asp.net - 在代码隐藏中将 ListView 字段绑定到值
- javascript - 一键添加/删除类
- javascript - 如何修复 NetSuite SuiteScript 未在“全额支付”发票上执行
- html - 悬停css不起作用,容器元素留在白色背景中
- bash - 从另一个 shell 脚本运行别名
- php - PHP 使用 preg_match 获取匹配的订单 ID
- php - laravel 会话存储的工作原理
- excel - Excel中单个单元格的2个独立MsgBoxs