简体   繁体   中英

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

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:

热图结果

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)

方形细胞

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

方形图

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');

热图 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM