Seaborn heatmap reducing cell size

Question:

Is there any way to change cell size of Seaborn heatmap?
I found this but I cannot get it work as expected.

So, I have long text in y-axis labels. Since all of the texts are chopped off, I would like to shrink cell size of the heatmap much smaller. I don’t need that big rectangle. (Highlighted just for example.)

enter image description here
(I hid label names.)

When I change the figure size by something like,

plt.figure(figsize=(8, 6)) or 
figure.set_size_inches(12, 12) 

the cell gets bigger as well so the texts remain chopped off.

Here is the code.

sns.set(font_scale=1.2)
ax0 = plt.axes()
ax1 = sns.heatmap(hmap, cbar=0, cmap="YlGnBu",linewidths=2, ax=ax0,vmax=3000, vmin=0)
ax1.set_title('test heatmap')

for item in ax1.get_yticklabels():
    item.set_rotation(0)

for item in ax1.get_xticklabels():
    item.set_rotation(0)

figure = plt.gcf()  # get current figure
figure.set_size_inches(12, 12)
plt.savefig('test.png') , dpi=400)
Asked By: K.K.

||

Answers:

You don’t actually want to change the cell size but you want to shrink the size of the axes. Ways to to this:

  • use plt.tight_layout()
  • Provide more space to the side e.g. via fig.subplots_adjust(left=0.4)
  • Create an axes, which has the size you want, ax1 = fig.add_axes([0.4,0.2,0.5,0.6]) (where the numbers are [left, bottom, width, height] and use this axes to plot the heatmap, sns.heatmap(... , ax=ax1).

Try using the square=True argument in your sns.heatmap call. This will constrain the heat map cells to a square aspect ratio.

ax1 = sns.heatmap(hmap, cbar=0, cmap="YlGnBu",linewidths=2, ax=ax0,vmax=3000, vmin=0, square=True)
Answered By: Nathan Watkins
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.