如何旋转带注释的 Seaborn 热图数据和图例?

Hor*_*aje 3 python plot matplotlib heatmap seaborn

我创建了一个seaborn 热图来总结Teils_U 系数。数据在热图中水平显示。现在,我想旋转数据和图例。我知道您可以在图中旋转 x 轴和 y 轴标签,但如何旋转数据和图例?

这是我的代码:

#creates padnas dataframe to hold the values
theilu = pd.DataFrame(index=['Y'],columns=matrix.columns)
#store column names in variable columns
columns = matrix.columns

#iterate through each variable
for j in range(0,len(columns)):
    #call teil_u function on "ziped" independant and dependant variable -> respectivley x & y in the functions section
    u = theil_u(matrix['Y'].tolist(),matrix[columns[j]].tolist())
    #select respecive columns needed for output
    theilu.loc[:,columns[j]] = u
    #handle nans if any  
    theilu.fillna(value=np.nan,inplace=True)

 #plot correlation between fraud reported (y) and all other variables (x)
 plt.figure(figsize=(20,1))
 sns.heatmap(theilu,annot=True,fmt='.2f')
 plt.show()
Run Code Online (Sandbox Code Playgroud)

这是我正在寻找的图像:

在此输入图像描述

如果您需要样本数据或 teil_u 函数来重现问题,请告诉我。谢谢

Joh*_*anC 8

可以通过 更改注释的参数annot_kws。其中之一是轮换。

颜色条的一些参数可以通过更改cbar_kwsdict,但不幸的是标签的方向不是其中之一。因此,您需要一个颜色条斧头的句柄。一种方法是预先创建一把斧头,并将其传递给sns.heatmap(..., cbar_ax=ax). 更简单的方法是事后获取句柄:cbar = heatmap.collections[0].colorbar

使用此ax手柄,您可以更改颜色栏的更多属性,例如其标签的方向。此外,可以更改它们的垂直对齐方式以使它们居中。

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

data = np.random.rand(1, 12)
fig, ax = plt.subplots(figsize=(10,2))
heatmap = sns.heatmap(data, cbar=True, ax=ax,
                      annot=True, fmt='.2f', annot_kws={'rotation': 90})
cbar = heatmap.collections[0].colorbar
# heatmap.set_yticklabels(heatmap.get_yticklabels(), rotation=90)
heatmap.set_xticklabels(heatmap.get_xticklabels(), rotation=90)
cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(), rotation=90, va='center')
plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)

示例图