简体   繁体   中英

How to create a single figure from subplots in for loop matplotlib

I have 4 images in numpy array format where each is a 4D (61, 73, 61, 11) and the last dimension coresponds to image channels (11 in my case). I use a for loop to iterate to the channels and at each iteration I create a subplot with 4 plots for each image. In the jupyter notebook I am able to see all the subplots but I want to create a single figure with all the subplots so I can create a single png and not 11. This is the code in matplotlib.

import maplotlib.pyplot as plt

center_slices = [s//2 for s in concat_img.shape[:1]] # take the middle slice
print(np.squeeze(concat_img[center_slices[0], :, :, 5]).shape)

for i in range(10):
    f, axarr = plt.subplots(1, 4, figsize=(20,5),  sharex=True);
    f.suptitle('Different intensity normalisation methods on brain fMRI image dual_regression + ALFF derivatives')

    img = axarr[0].imshow(np.squeeze(concat_img[:, :, center_slices[0], i]), cmap='gray');
    axarr[0].axis('off')
    axarr[0].set_title('Original image')
    f.colorbar(img, ax=axarr[0])

    img = axarr[1].imshow(np.squeeze(concat_img_white[:, :, center_slices[0], i]), cmap='gray');
    axarr[1].axis('off')
    axarr[1].set_title('Zero mean/unit stdev')
    f.colorbar(img, ax=axarr[1])

    img = axarr[2].imshow(np.squeeze(concat_img_zero_one[:, :, center_slices[0], i]), cmap='gray');
    axarr[2].axis('off')
    axarr[2].set_title('[0,1] rescaling')
    f.colorbar(img, ax=axarr[2])

    img = axarr[3].imshow(np.squeeze(concat_img_one_one[:, :, center_slices[0], i]), cmap='gray');
    axarr[3].axis('off')
    axarr[3].set_title('[-1,1] rescaling')
    f.colorbar(img, ax=axarr[3])
    
    f.subplots_adjust(wspace=0.05, hspace=0, top=0.8)
#     plt.savefig('./TTT.{0:07d}.png'.format(i)) # save each subplot in png 
plt.show();
   

在此处输入图片说明

Also a print screen with the output from jupyter for the first 5 rows.

UPDATE I tried to adjust the code according to @Timo answer in the comments using the following code :

center_slices = [s//2 for s in concat_img.shape[:1]]
print(np.squeeze(concat_img[center_slices[0], :, :, 5]).shape)

nrows , ncols = (11, 4)
fig, ax = plt.subplots(nrows=nrows, ncols=ncols,
                       figsize=(140, 120))
fig.suptitle('Different intensity normalisation methods on brain fMRI image dual_regression + ALFF derivatives')

# f.subplots_adjust(wspace=0.05, hspace=0, top=0.8)

zdata = [concat_img, concat_img_white, concat_img_zero_one, concat_img_one_one] 
titles =['Original image', 'Zero mean/unit stdev', '[0,1] rescaling', '[-1,1] rescaling']

for j in range(nrows):
    for i in range(ncols):
        img = zdata[i]
        cbar = ax[j, i].imshow(np.squeeze(img[:, :, center_slices[0], i]), cmap='gray', interpolation='nearest');
        ax[j, i].axis('off')
        ax[j, i].set_title(f'{titles[i]},channel :{j}')
        fig.colorbar(cbar, ax=ax[j, i])
        

fig.tight_layout()

Although the images are very small and have a lot of space between despite using tight layout

在此处输入图片说明

Solution

I manage to produce the plot and made this helper function

# Helper function
def myplot(nrows, ncols, zdata, global_title, title, savefig, name=None):

    center_slices = [s//2 for s in zdata[0].shape[:1]]
    print(np.squeeze(zdata[0][center_slices[0], :, :, 5]).shape)

    fig, ax = plt.subplots(nrows=nrows, ncols=ncols,
                       figsize=(5 * ncols, 4 * nrows))
    
    for j in range(nrows):
        for i in range(ncols):
            img = zdata[i]
            img = img[:, :, center_slices[0], j]
            cbar = ax[j, i].imshow(np.squeeze(img), cmap='gray', interpolation='nearest', aspect='auto');
            ax[j, i].axis('off')
            ax[j, i].set_title(f'{titles[i]},channel :{j}')
            fig.colorbar(cbar, ax=ax[j, i])

    fig.tight_layout()        
    fig.suptitle(global_title, fontsize=16, y=1.005)
    plt.show()
    st = fig.suptitle(global_title,  fontsize=16, y= 1.005)
    if savefig :
        fig.savefig(name, bbox_extra_artists=[st], bbox_inches='tight')

nrows = 11
ncols = 4

global_title ='Different intensity normalisation methods on brain fMRI image '
zdata = [concat_img, concat_img_white, concat_img_zero_one , concat_img_one_one]
titles =['Original image', 'Zero mean/unit stdev', '[0,1] rescaling', '[-1,1] rescaling']

myplot(nrows, ncols, zdata, global_title, titles, False)

This can be done by creating an axes instance with nrows != 1 . I have attached an example below.

import matplotlib.pyplot as plt
import numpy as np

nrows = 5
ncols = 4

xdata = np.linspace(-np.pi, np.pi)
ydata = 1 * xdata
X, Y = np.meshgrid(xdata, ydata)
zdata = np.sin(X + Y)

fig, ax = plt.subplots(nrows=nrows, ncols=ncols, sharex=True,
                       figsize=(nrows * 2.2, 2 * ncols))

for j in range(nrows):
    for i in range(ncols):
        cbar = ax[j, i].contourf(zdata)
        fig.colorbar(cbar, ax=ax[j, i])
        
fig.tight_layout()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM