【问题标题】:Adjust seaborn countplot by hue groups按色调组调整 seaborn 计数图
【发布时间】:2021-07-06 21:11:23
【问题描述】:

我有一个看起来像这样的数据集

status age_group
failure 18-25
failure 26-30
failure 18-25
success 41-50

等等……

sns.countplot(y='status', hue='age_group', data=data)

当我计算完整数据集时,我得到了这个 dataset countplot hued by age_group

问题如下,如何直接用seaborn绘制由每个age_group的出现n调整的图形?因为没有它,该图确实具有误导性,例如,>60 年龄组出现的最简单,因为该年龄组中有更多人。我搜索了文档,但它没有针对这种情况的任何内置函数。

提前致谢。

【问题讨论】:

    标签: python pandas matplotlib statistics seaborn


    【解决方案1】:

    显示比例的最简单方法是通过sns.histogram(..., multiple='fill')。要为年龄组和状态强制排序,创建有序类别会有所帮助。

    这是一些示例代码,使用 seaborn 0.11.1 进行测试:

    import matplotlib.pyplot as plt
    from matplotlib.ticker import PercentFormatter
    import seaborn as sns
    import numpy as np
    import pandas as pd
    
    data = pd.DataFrame({'status': np.random.choice(['Success', 'Failure'], 100, p=[.7, .3]),
                         'age_group': np.random.choice(['18-45', '45-60', '> 60'], 100, p=[.2, .3, .5])})
    data['age_group'] = pd.Categorical(data['age_group'], ordered=True, categories=['18-45', '45-60', '> 60'])
    data['status'] = pd.Categorical(data['status'], ordered=True, categories=['Failure', 'Success'])
    ax = sns.histplot(y='age_group', hue='status', multiple='fill', data=data)
    ax.xaxis.set_major_formatter(PercentFormatter(1))
    ax.set_xlabel('Percentage')
    plt.show()
    

    现在,为了创建问题的确切情节,一些 pandas 操作可能会创建以下数据框:

    • 计算每个年龄组和状态的值
    • 除以每个年龄组的总数

    也许可以采取一些捷径,但这就是我试图与熊猫玩杂耍的方式(编辑@PatrickFitzGerald 的评论:使用pd.crosstab()):

    # df = data.groupby(['status', 'age_group']).agg(len).reset_index(level=0) \
    #     .pivot(columns='status').droplevel(level=0, axis=1)
    # totals = df.sum(axis=1)
    # df['Success'] /= totals
    # df['Failure'] /= totals
    df = pd.crosstab(data['age_group'], data['status'], normalize='index')
    df1 = df.melt(var_name='status', value_name='percentage', ignore_index=False).reset_index()
    ax = sns.barplot(y='status', x='percentage', hue='age_group', palette='rocket', data=df1)
    ax.xaxis.set_major_formatter(PercentFormatter(1))
    ax.set_xlabel('Percentage')
    ax.set_ylabel('')
    plt.show()
    

    【讨论】:

    • 快捷方式:df = pd.crosstab(data['age_group'], data['status'], normalize='index')ax.xaxis.set_major_formatter('{x:.0%}')
    猜你喜欢
    • 1970-01-01
    • 2022-12-11
    • 2016-11-03
    • 2016-05-15
    • 2020-10-24
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    相关资源
    最近更新 更多