Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使子批次的大小相等?_Python_Python 3.x_Matplotlib - Fatal编程技术网

Python 如何使子批次的大小相等?

Python 如何使子批次的大小相等?,python,python-3.x,matplotlib,Python,Python 3.x,Matplotlib,我正在使用matplotlib和GridSpec在3x3子地块中绘制9幅图像 fig = plt.figure(figsize=(30,40)) fig.patch.set_facecolor('white') gs1 = gridspec.GridSpec(3,3) gs1.update(wspace=0.05, hspace=0.05) ax1 = plt.subplot(gs1[0]) ax2 = plt.subplot(gs1[1])

我正在使用matplotlib和GridSpec在3x3子地块中绘制9幅图像

    fig = plt.figure(figsize=(30,40))
    fig.patch.set_facecolor('white')
    gs1 = gridspec.GridSpec(3,3)
    gs1.update(wspace=0.05, hspace=0.05)
    ax1 = plt.subplot(gs1[0])
    ax2 = plt.subplot(gs1[1])
    ax3 = plt.subplot(gs1[2])
    ax4 = plt.subplot(gs1[3])
    ax5 = plt.subplot(gs1[4])
    ax6 = plt.subplot(gs1[5])
    ax7 = plt.subplot(gs1[6])
    ax8 = plt.subplot(gs1[7])
    ax9 = plt.subplot(gs1[8])
    ax1.imshow(img1,cmap='gray')
    ax2.imshow(img2,cmap='gray')
    ...
    ax9.imshow(img9,cmap='gray')
但是,每行的图像大小不同。例如,第一行图像大小为256x256,第二行图像大小为200x200,第三行图像大小为128x128

我想以相同的大小在子图中绘制图像。我应该如何在python中使用它?谢谢

这是4x3子批次的一个示例

不要使用
matplotlib.gridspec
,而是使用
图。添加子图
,如下面的可运行代码所示。但是,在进行某些打印时,需要
启用自动缩放(False)
以抑制其大小调整行为

import numpy as np
import matplotlib.pyplot as plt

# a function that creates image array for `imshow()`
def make_img(h):
    return np.random.randint(16, size=(h,h)) 

fig = plt.figure(figsize=(8, 12))
columns = 3
rows = 4
axs = []

for i in range(columns*rows):
    axs.append( fig.add_subplot(rows, columns, i+1) )

    # axs[-1] is the new axes, write its title as `axs[number]`
    axs[-1].set_title("axs[%d]" % (i))

    # plot raster image on this axes
    plt.imshow(make_img(i+1), cmap='viridis', alpha=(i+1.)/(rows*columns))

    # maniputate axs[-1] here, plot something on it
    axs[-1].set_autoscale_on(False)   # suppress auto sizing
    axs[-1].plot(np.random.randint(2*(i+1), size=(i+1)), color="red", linewidth=2.5)


fig.subplots_adjust(wspace=0.3, hspace=0.4)
plt.show()
结果图:


我想您希望以不同的大小显示图像,以便不同图像的所有像素大小相同

这通常很难,但对于子地块网格的行(或列)中的所有图像都具有相同大小的情况,这变得很容易。可以使用gridspec的
height\u ratio
(或
width\u ratio
(如果是列)参数并将其设置为图像的像素高度(宽度)


查看此链接是否有助于您:抱歉。我有9张不同大小的图片。如何将其打印到3x3子地块,以便子地块的大小必须相同。对不起,误会了
import matplotlib.pyplot as plt
import numpy as np

images = [np.random.rand(r,r) for r in [25,20,12] for _ in range(3)]


r = [im.shape[0] for im in images[::3]]
fig, axes = plt.subplots(3,3, gridspec_kw=dict(height_ratios=r, hspace=0.3))

for ax, im in zip(axes.flat, images):
    ax.imshow(im)


plt.show()