首页 > 解决方案 > Matplotlib 不均匀网格 imshow()

问题描述

我已经将 5 个 numpy 数组的内容绘制为带有matplotlib.pyplot.imshow(). 下面的代码示例:

fig, axarr = plt.subplots(2, 3)
fig.set_size_inches(10, 10)
axarr[0, 0].imshow(img1)
axarr[0, 0].axis('off')
axarr[0, 1].imshow(img2)
axarr[0, 1].axis('off')
axarr[0, 2].imshow(img3)
axarr[0, 2].axis('off')
axarr[1, 0].imshow(img4)
axarr[1, 0].axis('off')
axarr[1, 2].imshow(img5)
axarr[1, 2].axis('off')
axarr[1, 1].axis('off')
plt.subplots_adjust(wspace=0, hspace=0)
plt.savefig(predictions)
plt.close()

这会产生以下输出:

示例图

如何绘制图像,以便底行的 2 个图像并排并以该行为中心?

标签: pythonmatplotlibdata-visualization

解决方案


有许多可能的解决方案。这是生成其中一个的工作代码。在代码中,图像被并排附加以仅获得 2 个绘制的结果图像。

import matplotlib.pyplot as plt
import numpy as np

# make up images for demo purposes
raw = np.random.randint(10, size=(6,6))
im0 = (raw >= 5) * 1                     # get either 0 or 1 in the array
im1 = np.random.randint(10, size=(6,6))  # get 0-9 in the array

# combine them to get 2 different images
im_01 = np.append(im0, im1, axis=1)      # 2 images (O+1), side-by-side combined
im_010 = np.append(im_01, im0, axis=1)   # 3 images (O+1+0)

# create figure with 2 axes in 2 rows, 1 column
fig, (ax0, ax1) = plt.subplots(nrows=2, ncols=1)
width = 10
fig.set_size_inches((width, width/2.))  # need proper (width, height) ratio

# plot (3 combined) image in row1
ax0.imshow( im_010 )
ax0.axis('off')

# plot (2 combined) image in row2
ax1.imshow( im_01 )
ax1.axis('off')

plt.show()

结果图:

在此处输入图像描述


推荐阅读