首页 > 解决方案 > 使用子图时 Seaborn 热图宽度不匹配

问题描述

我正在尝试将我的第二个子图(带有二进制 cmap 的列总和)的宽度调整为第一个子图的宽度。

到目前为止,我只能通过随机选择不同的 figsize 来做到这一点,但是每次我尝试在不同大小的数据集上重新使用代码时,我总是想出如下图所示的内容(第二个热图总是比第一个宽)。

我错过了自动调整第二个的东西吗?

在此处输入图像描述

import matplotlib.pyplot as plt    
import seaborn as sns   
import pandas as pd
test = pd.DataFrame({'user': ['Bob', 'Bob', 'Bob','Janice','Janice','Fernand','Kevin','Sidhant'], 
                     'tag' : ['enfant','enfant','enfant','femme','femme','jeune','jeune','jeune'],
                   'income': [3, 5, 1,14,8,10,13,17]})
  
# specify font sizes for later:

titlesize= 30
ticklabel = 23
legendlabel = 23

# Generate custom diverging colormaps:

cmap = sns.color_palette("ch:18,-.1,dark=.3",  6)
cmap2 = sns.color_palette("binary",  6)

# Preparing data for the heatmap:

heatmap1_data = pd.pivot_table(test, values='income', 
                                 index=['user'], 
                                 columns='tag')
heatmap1_data = heatmap1_data.reindex(heatmap1_data.sum().sort_values(ascending=False).index, axis=1)

# Creating figure:

fig, (ax1, ax2) = plt.subplots(2,1,figsize=(10,15))

# First subplot:

sns.heatmap(heatmap1_data, ax= ax1, cmap=cmap,square=True, linewidths=.5, annot=True, cbar = False,annot_kws={"size": legendlabel} )

# Cosmetic first subplot:

ax1.xaxis.tick_top()
ax1.tick_params(labelsize= ticklabel, top = False)
ax1.set_xlabel('')
ax1.set_ylabel('')
ax1.set_xticklabels(heatmap1_data.columns,rotation=90)
ax1.set_yticklabels(heatmap1_data.index,rotation=0)
ax1.set_title("Activités par agence et population vulnérable", size= titlesize, pad=20)

# Second subplot (column sum at the bottom):

sns.heatmap((pd.DataFrame(heatmap1_data.sum(axis=0))).transpose().round(1), ax=ax2, square=True, fmt='g', linewidths=.5, annot=True, cmap=cmap2 , cbar=False, xticklabels=False, yticklabels=False, annot_kws={"size": legendlabel})
ax2.set_xlabel("Nombre d'activités", size = ticklabel, labelpad = 5)

# More cosmetic:

ax1.set_title("Title", size= titlesize, pad=35)
ax1.set_xlabel('')
ax1.set_ylabel('')
plt.tick_params(labelsize= ticklabel,left=False, bottom=False)
plt.xticks(rotation=60)
ax1.spines['bottom'].set_color('#dfe1ec')
ax1.spines['left'].set_color('#dfe1ec')
ax1.spines['top'].set_color('#dfe1ec')
ax1.spines['right'].set_color('#dfe1ec')
plt.tight_layout()

plt.show()

标签: pythonmatplotlibsumseabornheatmap

解决方案


问题是使用square=Truein sns.heatmap。由于两个子图的纵横比是宽还是高,因此“平方”的完成方式各不相同。首先,它做得更薄,其次,它做得更短。这样做是为了适应子图轴大小的约束,当您调用plt.subplots.

解决此问题的一种方法是将两个轴的纵横比定义为不同并适合数据的形状。这不会在 100% 的时间里起作用,但在大多数情况下会起作用。您可以在调用中使用关键字gridspec_kw并定义字典。'height_ratios'plt.subplots

fig, (ax1, ax2) = plt.subplots(2,1, figsize=(10,15), gridspec_kw={'height_ratios':[5, 1]})

在此处输入图像描述


推荐阅读