Centering A Table With A Heatmap
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],
Solution 1:
Short method
You can move/resize the table with Axes.set_position()
. The left
/bottom
/width
/height
params can be tweaked as needed:
bbox1 = ax1.get_position()
bbox2 = ax2.get_position()
# modify as needed
left = bbox1.x0
bottom = bbox1.y0 - (bbox2.height * 0.8)
width = bbox1.x0 + (bbox1.width * 0.8)
height = bbox2.height
ax2.set_position([left, bottom, width, height])
Longer method
If the simple method isn't working well, try setting the axes height_ratios
via gridspec_kw
in plt.subplots()
. Also I needed to set tight_layout=False
.
Use height_ratios
to set the ratio of ax1:ax2
(heatmap:table), and use the *_offset
variables to adjust the table's size/position as needed. These were values that worked for my system, but you can tweak for your system:
### modify these params as needed ###
height_ratios = (20, 1) # heatmap:table ratio (20:1)
left_offset = 0# table left position adjustment
bottom_offset = -0.025# table bottom position adjustment
width_offset = -0.0005# table width adjustment
height_offset = 0# table height adjusment#####################################
fig_kw = dict(figsize=(18, 18), dpi=200, tight_layout=False)
gridspec_kw = dict(height_ratios=height_ratios)
fig, (ax1, ax2) = plt.subplots(nrows=2, gridspec_kw=gridspec_kw, **fig_kw)
sns.heatmap(df_norm, ax=ax1, annot=df, cmap='RdBu_r', cbar=True)
ax2.table(cellText=[df_info.iloc[row] for row inrange(len(df_info))],
rowLabels=table.index,
colLabels=None,
loc='center')
ax2.axis('off')
bbox1 = ax1.get_position()
bbox2 = ax2.get_position()
left = bbox1.x0 + left_offset
bottom = bbox1.y0 - bbox2.height + bottom_offset
width = bbox1.width + width_offset
height = bbox2.height + height_offset
ax2.set_position([left, bottom, width, height])
Post a Comment for "Centering A Table With A Heatmap"