简体   繁体   中英

matplotlib combining subplots into a single plot with no axis and no gaps

I have an image which looks like so:

在此处输入图像描述

It was generated using matplotlib using:

for slice_idx in range(mandrill_t.highpasses[1].shape[2]):
    print(slice_idx)
    subplot(2, 3, slice_idx+1)
    imshow(np.abs(mandrill_t.highpasses[1][:,:,slice_idx]), cmap='Spectral', clim=(0, 1))

However, for my use case, I would like all these 6 images in a single image with no gaps or axis - I do not have an example output image to show, but essentially, I would like them stacked horizontally (3 of them) and vertically (2 of them) so that the 6 images are a single image.

I tried looking around for similar problems to draw inspiration from, but no luck so far :(

Any pointers would be great.

That's what GridSpec is for (see plt.subplots docs ):

Just add the following line at the start:

subplots(2, 3, gridspec_kw={"wspace": 0, "hspace": 0})

You might also have to set some plot elements to invisible but it's hard to figure out exactly which without an MCVE.

You have to specify the grid parameters:

  • 2 rows
  • 3 columns
  • 0 width space
  • 0 height space

with matplotlib.pyplot.subplots :

fig, axes = plt.subplots(nrows = 2, ncols = 3, gridspec_kw = {'wspace': 0, 'hspace': 0})

Then you can loop over created axes and, for each one of them, you have to show the image and set axis to 'tight' firtsly and 'off' secondly:

for ax in axes.flatten():
    ax.imshow(img)
    ax.axis('tight')
    ax.axis('off')

Your code would be slighlty different, since you are plotting different images for each ax .

Complete Code

import matplotlib.pyplot as plt

img = plt.imread('img.jpeg')

fig, axes = plt.subplots(nrows = 2, ncols = 3, gridspec_kw = {'wspace': 0, 'hspace': 0})

for ax in axes.flatten():
    ax.imshow(img)
    ax.axis('tight')
    ax.axis('off')

plt.show()

在此处输入图像描述

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