I'm trying to make a grid of images in matplotlib using gridspec. The problem is, I can't seem to get it to get rid of the padding between the rows.
Here's my attempt at the solution.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np
from os import listdir
from os import chdir
from PIL import Image
import matplotlib.gridspec as gridspec
chdir('/home/matthew/Dropbox/Work/writing/'+
'paper_preperation/jump_figs')
files = listdir('/home/matthew/Dropbox/Work/writing/'+
'paper_preperation/jump_figs')
images = [Image.open(f) for f in files]
"""
fig = plt.figure()
grid = ImageGrid(fig, 111, # similar to subplot(111)
nrows_ncols = (2, 5), # creates 2x2 grid of axes
axes_pad=0.1, # pad between axes in inch.
)
"""
num_rows = 2
num_cols = 5
fig = plt.figure()
gs = gridspec.GridSpec(num_rows, num_cols, wspace=0.0)
ax = [plt.subplot(gs[i]) for i in range(num_rows*num_cols)]
gs.update(hspace=0)
#gs.tight_layout(fig, h_pad=0,w_pad=0)
for i,im in enumerate(images):
ax[i].imshow(im)
ax[i].axis('off')
#ax_grid[i/num_cols,i-(i/num_cols)*num_cols].imshow(im) # The AxesGrid object work as a list of axes.
#ax_grid[i/num_cols,i-(i/num_cols)*num_cols].axis('off')
"""
all_axes = fig.get_axes()
for ax in all_axes:
for sp in ax.spines.values():
sp.set_visible(False)
if ax.is_first_row():
ax.spines['top'].set_visible(True)
if ax.is_last_row():
ax.spines['bottom'].set_visible(True)
if ax.is_first_col():
ax.spines['left'].set_visible(True)
if ax.is_last_col():
ax.spines['right'].set_visible(True)
"""
plt.show()
Also does anyone know how to make each subplot bigger?
To remove whitespaces at the bottom of a Matplotlib graph, we can use tight layout or autoscale_on=False.
We can use the plt. subplots_adjust() method to change the space between Matplotlib subplots. The parameters wspace and hspace specify the space reserved between Matplotlib subplots.
Hide the Whitespaces and Borders in Matplotlib Figure To get rid of whitespace around the border, we can set bbox_inches='tight' in the savefig() method. Similarly, to remove the white border around the image while we set pad_inches = 0 in the savefig() method.
For me a combination of aspect="auto"
and subplots_adjust
worked. Also I always try to make the subplots quadratic. For the individual subplot size figsize
can be adjusted.
fig, axes = plt.subplots(nrows=max_rows, ncols=max_cols, figsize=(20,20))
for idx, image in enumerate(images):
row = idx // max_cols
col = idx % max_cols
axes[row, col].axis("off")
axes[row, col].imshow(image, cmap="gray", aspect="auto")
plt.subplots_adjust(wspace=.05, hspace=.05)
plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With