I have a column of matshow images and below the bottom one I want to place a colorbar with a width that is the same as that of the image(s).
I tried following the suggestion of Set Matplotlib colorbar size to match graph but implementing this shrinks the bottom plot:
MWE:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
fig, axes = plt.subplots(nrows=2, ncols=1, dpi=200)
for ax in axes.flat:
im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)
divider = make_axes_locatable(axes[1])
cax = divider.append_axes("bottom", size="5%", pad=0.25)
fig.colorbar(im, orientation='horizontal', cax=cax)
plt.show()
If you pass the original array of axes to colorbar
then the colorbar axes is automatically created by stealing space from both of them. Using compressed layout ensures that the colorbar is the right size relative to the original axes.
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, ncols=1, layout='compressed')
for ax in axes.flat:
im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)
fig.colorbar(im, orientation='horizontal', ax=axes)
plt.show()