Combine two heatmaps (different sizes), maintaing same cell size, the same color bar and the same x-axis (GridSpec),

I am trying to combine two heatmaps of different row numbers. I want to keep the same cell size for both, and that they have the same x-axis and the same color bar.

Here is what I tried so far.

import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.gridspec import GridSpec
fig = plt.figure()

gs=GridSpec(16,18)

ax1 = fig.add_subplot(gs[0:6,:])
ax2 = fig.add_subplot(gs[7:17,:])

sns.heatmap(site, cmap="inferno", ax=ax1)
sns.heatmap(country, cmap="inferno", ax=ax2)

Here is the output:

enter image description here

Thank you very much.

Upvotes: 1

Views: 801

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40737

You can play with the height_ratios of GridSpec:

import matplotlib.gridspec as gs

site = np.random.random(size=(2,20))
country = np.random.random(size=(20,20))

fig = plt.figure()
N_rows_site, _ = site.shape
N_rows_country, _ = country.shape

grid=gs.GridSpec(2,2, height_ratios=[N_rows_site,N_rows_country], width_ratios=[50,1])

ax1 = fig.add_subplot(grid[0,0])
ax2 = fig.add_subplot(grid[1,0], sharex=ax1)
cax = fig.add_subplot(grid[:,1])

sns.heatmap(site, cmap="inferno", ax=ax1, cbar_ax=cax)
sns.heatmap(country, cmap="inferno", ax=ax2, cbar_ax=cax)
plt.setp(ax1.get_xticklabels(), visible=False)

enter image description here

with a different number of lines:

site = np.random.random(size=(10,20))
country = np.random.random(size=(20,20))

enter image description here

Upvotes: 2

Related Questions