I want to create a figure which contains three different heatmap subplots. All three supblots should be aligned per row, as they have a common meaning. But the width of each subplot is different, and when combining them I get different heights, so the rows are not aligned.
How can I solve it?
Here is a minimal code example and a picture [1].
import numpy as np
from matplotlib.gridspec import GridSpec
rows = 4
first_cols = 5
second_cols = 1
third_cols = 3
first = np.random.randint(0,2,( rows , first_cols ))
second = np.random.randint(0,2,( rows , second_cols ))
third = np.random.randint(0,4,( rows , third_cols ))
fig=plt.figure()
gs=GridSpec(1,first_cols+second_cols+third_cols)
ax1=fig.add_subplot(gs[0,0:first_cols])
ax2=fig.add_subplot(gs[0,first_cols:first_cols+second_cols])
ax3=fig.add_subplot(gs[0,first_cols+second_cols:])
im1 = ax1.imshow(first)
im2 = ax2.imshow(second)
im3 = ax3.imshow(third)
plt.show()
By placing your axes over multiple GridSpec
columns they incorporate the width of the gaps between the columns so are wider (and therefore taller) than you want. You can instead create your GridSpec
with just three columns of different widths.
gs=GridSpec(1, 3, width_ratios=[first_cols, second_cols, third_cols])
ax1=fig.add_subplot(gs[0,0])
ax2=fig.add_subplot(gs[0,1])
ax3=fig.add_subplot(gs[0,2])
A shortcut to this without using a GridSpec
directly is
fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, width_ratios=[first_cols, second_cols, third_cols])