【问题标题】:how to easily group values to improve heatmap visualization如何轻松对值进行分组以改进热图可视化
【发布时间】:2020-06-29 01:40:39
【问题描述】:

我正在制作热图。我得到了一个数据框,现在正在比较值“Age”和“purch_bike”(这是一个“是”或“否”变量)。我想清理这个视觉效果,因为热图上当前显示的值太多了。所以我想我想为年龄创建更大的范围,通过将它们分组到 11 的箱/间隔中。我该怎么做?

数据集:http://www.ishelp.info/data/bikebuyers_original.csv

当前代码和输出(通过 Google Colab):

sns.heatmap(pd.crosstab(df.Age, df.purch_bike), annot=True, fmt='d');
chi1, p_value1, dof1, expected1 = chi2_contingency(pd.crosstab(df['Age'], df['purch_bike']))
print(f'X square:\t\t{round(chi1, 4)}') # this code simply displays the Chi-square stat and p-value
print(f'p-value:\t\t{round(p_value1, 6)}')
plt.show()

【问题讨论】:

    标签: python python-3.x matplotlib seaborn heatmap


    【解决方案1】:

    pd.cut 来自 pandas 每个范围的分组。它可用于创建一个新列“AgeGroup”,用作pd.crosstab 的输入。 pd.cut 的 labels 参数可以设置适当的文本用作 y-ticks。 right=False 处理与 bin 边界相等的年龄,将它们放在较高的 bin 中。 一些示例代码:

    import matplotlib.pyplot as plt
    import pandas as pd
    import seaborn as sns
    
    df = pd.read_csv('http://www.ishelp.info/data/bikebuyers_original.csv')
    df.rename(columns={"Purchased Bike": "purch_bike"}, inplace=True)
    
    # bins = list(range(0, 80, 10)) + [120]
    bins = [20, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 120]
    labels = [f'{a0}-{a1 - 1}' for a0, a1 in zip(bins[:-2], bins[1:-1])] + [f'≥{bins[-2]}']
    df['AgeGroup'] = pd.cut(df.Age, bins=bins, labels=labels, right=False)
    
    sns.heatmap(pd.crosstab(df.AgeGroup, df.purch_bike), annot=True, fmt='d')
    plt.yticks(rotation=0)
    plt.show()
    

    【讨论】:

    • 我怎样才能准确地创建 10 个垃圾箱?年龄分为20-27、28-34、35-41、42-48、49-55、56-62、63-69、70-76、77-83、84-90
    • bins = [20, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 120]
    猜你喜欢
    • 2012-01-26
    • 1970-01-01
    • 2022-08-11
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多