I'm trying to create a 4x2 plot on a slightly non-rectangular dataset (x-axis range is smaller than y-axis range) using plt.subplots
and assign colorbars using make_axes_locatable
to have the colorbars nice and flush wih the subplots. I always end up with huge paddings/margins between the two subplot columns which I suspect originate from the colorbars... I've tried multiple things from many stackoverflow questions (e.g. using fig.subplots_adjust()
, constrained_layout=True
etc.) but to no avail. The margins between the two columns stay really large (see img below) and make the image unreadable...
Any input would be much appreciated!
Code used to reproduce the issue:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
data = np.random.random((10, 6))
fig, axs = plt.subplots(nrows=4, ncols=2, figsize=(16, 8), sharex=True, sharey=False, constrained_layout=True)
for idx in range(4):
# plot image
im1 = axs[idx, 0].imshow(data, cmap=cm.coolwarm)
im2 = axs[idx, 1].imshow(data, cmap=cm.viridis)
# make colorbars
ax1_divider = make_axes_locatable(axs[idx, 0])
cax1 = ax1_divider.append_axes("right", size="2%", pad=0.05)
cb1 = fig.colorbar(im1, cax=cax1, orientation="vertical")
ax2_divider = make_axes_locatable(axs[idx, 1])
cax2 = ax2_divider.append_axes("right", size="2%", pad=0.05)
cb2 = fig.colorbar(im2, cax=cax2, orientation="vertical")
CodePudding user response:
You are plotting multiple images (which by default it tries to keep an equal aspect ratio), in which the height is greater than the width. Therefore, total height of the images > total width of the images.
It follows that one way to reduce the white spacing between columns is to reduce the width of the figure.
Try setting this:
fig, axs = plt.subplots(nrows=4, ncols=2, figsize=(4, 8), sharex=True, sharey=False, constrained_layout=True)