Home > Software design >  How to make a square heatmap (overal plot, not the cells)
How to make a square heatmap (overal plot, not the cells)

Time:01-02

The square attribute in sns.heatmap works in weird manner. When I plot a heatmap using random numbers and use the square attribute, it works fine.

Random heatmap using numpy

When I plot the heatmap with my matrix, it creates the heatmap properly.

enter image description here

However, when I use the square attribute, the plot becomes a tiny square.

enter image description here

I can't figure out what is going wrong over here.

CodePudding user response:

Well, square=True means: "show all cells as squares". The only way to fit 7x560 squares into the plot region is reducing the height by a factor of about 80. In other words: it is strongly recommended to use square=False for data that has such a large difference between horizontal and vertical directions. Seaborn isn't doing anything wrong here, it just gives you want you asked for.

If you want the heatmap to be square (instead of the cells), you can use ax = sns.heatmap(data, square=False) and then ax.set_aspect(data.shape[1] / data.shape[0]).

Here is an example:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

data = np.random.randn(7, 560).cumsum(axis=1).cumsum(axis=0)
data -= data.min(axis=1, keepdims=True)
data /= data.max(axis=1, keepdims=True)

ax = sns.heatmap(data, cmap='turbo', cbar=True, xticklabels=50,
                 yticklabels=['Grumpy', 'Dopey', 'Doc', 'Happy', 'Bashful', 'Sneezy', 'Sleepy'])
ax.set_aspect(data.shape[1] / data.shape[0])
ax.tick_params(labelrotation=0)
plt.tight_layout()
plt.show()

square sns.heatmap

  • Related