How do I fix plt.subplots to bring the plots closer together?

Question:

I am plotting 27 maps, or 9 rows and 3 columns. I am using plt.subplots to plot them, but I am struggling to bring the plots closer together? I tried both:

plt.tight_layout()  
fig.tight_layout()

But I keep getting this error anytime I add that in:

ValueError: zero-size array to reduction operation minimum which has no identity

This is my code so far with the plt.subplot and mapping, it appears to be working but the map layout is not very readable:

fig, axes = plt.subplots(nrows=9, ncols=3,  figsize=(60,44), subplot_kw=dict(projection=ccrs.PlateCarree()))
for i,t,ax in zip(range(27),time_years, axes.ravel()):
    ax.set_extent([-90, 10, 5, 85], crs=ccrs.PlateCarree())
    x = ax.contourf(longitude,latitude,yearly_means[i],10, extend='both')
    ax.add_feature(cfeature.LAND, zorder=100, edgecolor='k')
    ax.coastlines()
    gridlines = ax.gridlines(draw_labels=True)
    gridlines.xlabels_top = False
    gridlines.ylabels_right = False
    ax.text(.5,-.11, 'Longitude' , va='bottom' , ha='center', rotation='horizontal', rotation_mode= 'anchor',transform=ax.transAxes)
    ax.text(-.15, .5, 'Latitude' , va='bottom' , ha='center', rotation='vertical', rotation_mode= 'anchor',transform=ax.transAxes)
    ax.set_title('extremes for %d' %t)
cbar = fig.colorbar(x, orientation='horizontal', ax = axes,fraction=.046, pad=0.04)
cbar.set_label('psu', labelpad=15, y=.5, rotation=0)
#plt.tight_layout()
plt.subplots_adjust(wspace=None, hspace=None) # THIS DOES NOT WORK, no change
plt.show()  

enter image description here

I tried adding: plt.subplots_adjust to make the width between plots smaller, but there is no difference when I add that line.
How do I bring these plots closer together and make the figures bigger? Also the colorbar overlaps on the image, why might be that happening?

Asked By: wabash

||

Answers:

The first thing to try is plt.tight_layout() – it will automatically adjust paddings around subplots. Another thing to play with is figsize and its aspect ratio to make it consistent with your subplots alignment. In your case, the canvas is too wide for the subplots.

Answered By: freude

plt.tight_layoutdoesn’t remove the padding between the plots automatically but rather fixes overlapping issues.
you can try the pad options described in plt.tight_layout documentation

what will probably work better/best is to use fig, ax = plt.subplots(9,3, figsize=(9,6), layout="compressed")
with emphasis on layout="compressed" which should help in your case of maps/ images layout=compressed

Answered By: user20068036