This code
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid
mat0 = [[1, 2], [3, 4], [5, 6], [7, 8]] # 4 rows × 2 columns
mat1 = [[-2, 0, 2, 4], [0, 2, 4, 6]] # 2 rows × 4 columns
fig = plt.figure(figsize=(9, 3))
grid = AxesGrid(fig, 111, nrows_ncols=(1,2),
axes_pad=0.15,
cbar_size="6%", cbar_location="right", cbar_mode="single")
for ax, mat in zip(grid.axes_all, (mat0, mat1)): im = ax.imshow(mat)
grid.cbar_axes[0].colorbar(im)
plt.figure()
plt.imshow(mat0)
plt.colorbar()
plt.show()
produces two Figures
I expected to see, in the first one, a tall rectangle in the left, as in the second Figure.
Of course I'm not understanding what is really happening with AxesGrid.
How can I have the two Images side by side, without the tall one being truncated?
Is an image worth 1000 words?
If you're dealing with images of different dimensions, it can be tricky to display them side by side with equal height while maintaining their aspect ratio. A simpler alternative, and for me a more elegant solution, might be to just use subplots and share the colorbar. Here's how you can do it:
import matplotlib.pyplot as plt
import numpy as np
mat0 = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) # 4 rows × 2 columns
mat1 = np.array([[-2, 0, 2, 4], [0, 2, 4, 6]]) # 2 rows × 4 columns
fig, axs = plt.subplots(1, 2, figsize=(9, 3))
cax = axs[0].imshow(mat0)
axs[1].imshow(mat1)
fig.colorbar(cax, ax=axs.ravel().tolist(), shrink=0.5)
plt.show()
In this script, subplots
creates a 1x2 grid of axes. The images are displayed on these axes using imshow
. The colorbar is shared across the subplots with the help of fig.colorbar
. The shrink
parameter adjusts the size of the colorbar. You may need to adjust the figsize
parameter to better suit your data and display size.
I hope this helps.