python - 使用子图时 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()
解决方案
问题是使用square=True
in 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]})
推荐阅读
- powershell - 如何使用 Gmail 作为 SMTP 服务器发送邮件
- java - Java PreparedStatement 设置 NULL 参数
- sqlalchemy - geoalchemy 将线串和多线串与 Z 的混合插入到 postgis
- javascript - 如何使用用户属性更改 MapboxGL 中的 line-dasharray 设置?
- excel - 使用 VBA 根据标准查找和填写其他 Excel 工作表
- ios - 应用程序启动卡住了黑屏。这种情况偶尔发生。大多数时候优雅地启动没有任何问题
- ios - 在三个视图控制器之间导航,其中三个视图控制器都在一个选项卡栏视图中
- websocket - 未通过 websockets 从 mosquitto 接收有效负载
- php - 是否有检查参数是否存在且大于零的速记方法?
- asp.net - 如何从母版页上的链接中获取文本?