【问题标题】:How can I rotate annotated seaborn heatmap data and legend?如何旋转带注释的 seaborn 热图数据和图例?
【发布时间】:2020-08-10 06:19:24
【问题描述】:

我创建了一个 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()

这是我正在寻找的图像:

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

【问题讨论】:

    标签: python matplotlib plot seaborn heatmap


    【解决方案1】:

    注解的参数可以通过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()
    

    【讨论】:

    • 感谢您的回答,非常有帮助!
    【解决方案2】:

    您可以使用the annot_kws= argument 将参数传递给ax.text()(用于编写注释)。

    因此:

    flights = sns.load_dataset("flights")
    flights = flights.pivot("month", "year", "passengers")
    fig, ax = plt.subplots(figsize=(8,8))
    ax = sns.heatmap(flights, annot=True, fmt='d', annot_kws={'rotation':90})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-01
      • 2020-04-19
      • 2016-01-14
      • 2015-09-27
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      相关资源
      最近更新 更多