How to print the heatmap in a square shape using seaborn?

Viewed 404

When I run the code below I notice that the heatmap does not have a square shape knowing that I have used square=True but it did not work! Any idea how can I print the heatmap in a square format? Thank you!

The code:

from datetime import datetime
import numpy as np
import pandas as pd
import matplotlib as plt
import os
import seaborn as sns

temp_hourly_A5_A7_AX_ASHRAE=pd.read_csv('C:\\Users\\cvaa4\\Desktop\\projects\\s\\temp_hourly_A5_A7_AX_ASHRAE.csv',index_col=0, parse_dates=True, dayfirst=True, skiprows=2)
sns.heatmap(temp_hourly_A5_A7_AX_ASHRAE,cmap="YlGnBu", vmin=18, vmax=27, square=True, cbar=False, linewidth=0.0001);

The result:

heatmap result

2 Answers

square=True should work to have square cells, below is a working example:

import pandas as pd
import numpy as np
import seaborn as sns

df = pd.DataFrame(np.tile([0,1], 15*15).reshape(-1,15))

sns.heatmap(df, square=True)

square cells

If you want a square shape of the plot however, you can use set_aspect and the shape of the data:

ax = sns.heatmap(df)
ax.set_aspect(df.shape[1]/df.shape[0]) # here 0.5 Y/X ratio

square plot

You can use matplotlib and set a figsize before plotting heatmap.

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
rnd = np.random.default_rng(12345)
data = rnd.uniform(-100, 100, [100, 50])

plt.figure(figsize=(6, 5))
sns.heatmap(data, cmap='viridis');

heatmap seaborn

Note that I used figsize=(6, 5) rather than a square figsize=(5, 5). This is because on a given figsize, seaborn also puts the colorbar, which might cause the heatmap to be squished a bit. You might want to change those figsizes too depending on what you need.

Related