I'm trying to add a matplotlib table under a seaborn heatmap. I've been able to plot them but no luck with the alignment.
# Main data
df = pd.DataFrame({"A": [20, 10, 7, 39],
"B": [1, 8, 12, 9],
"C": [780, 800, 1200, 250]})
# It contains min and max values for the df cols
df_info = pd.DataFrame({"A": [22, 35],
"B": [5, 10],
"C": [850, 900]})
df_norm = (df - df.min())/(df.max() - df.min())
# Plot the heatmap
vmin = df_norm.min().min()
vmax = df_norm.max().max()
fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
sns.heatmap(df_norm, ax=ax1, annot=df, cmap='RdBu_r', cbar=True)
When I add the table to the ax2 it's plotted taking all the width of the heatmap (color bar included). I've tried all possible combination of locor bbox but I haven't been able to center exactly the table and giving it the same width (of the whole table but also of the single cells) of the heatmap at the top.
table = df_info
cell_text = []
for row in range(len(table)):
cell_text.append(table.iloc[row])
ax2.axis('off')
ax2.table(cellText=cell_text,
rowLabels=table.index,
colLabels=None,
loc='center')
Also sometimes I pass to the heatmap the param square=True to print squared cells and the result is this:
Question: How can I attach and center the table and its cells to the heatmap?
EDIT: Technically tdy's answer is correct to solve the problem of my simple example. Although I might have over-simplified it and left out an important piece of information.
In my real case scenario, if I create the figure with:
fig, (ax1, ax2) = plt.subplots(nrows=2,
**{"figsize": (18, 18),
"dpi": 200,
"tight_layout": True})
and apply the above mentioned answer I obtain something like this:
Where the table is way far at the bottom and wider than the heatmap.
Also if I set tight_layout=False I obtain a table with the correct width but still very far at the bottom:
fig, (ax1, ax2) = plt.subplots(nrows=2,
**{"figsize": (18, 18),
"dpi": 200,
"tight_layout": False})
I guess in my case the "figsize": (18, 18) and tight_layout have big impact on my problem but I'm not sure neither why nor how to solve it.





