gpt4 book ai didi

python - Seaborn.countplot : order categories by count, 也按类别?

转载 作者:行者123 更新时间:2023-11-30 21:56:54 24 4
gpt4 key购买 nike

所以我了解如何对条形图进行排序(即 here )。但我找不到的是如何按子类别之一对条形图进行排序。

例如,给定以下数据框,我可以获得条形图。但我想做的是,按照 ClassicType 从大到小排序。

import pandas as pd

test_df = pd.DataFrame([
['Jake', 38, 'MW', 'Classic'],
['John', 38,'NW', 'Classic'],
['Sam', 34, 'SE', 'Classic'],
['Sam', 22, 'E' ,'Classic'],
['Joe', 43, 'ESE2', 'Classic'],
['Joe', 34, 'MTN2', 'Classic'],
['Joe', 38, 'MTN2', 'Classic'],
['Scott', 38, 'ESE2', 'Classic'],
['Chris', 34, 'SSE1', 'Classic'],
['Joe', 43, 'S1', 'New'],
['Paul', 34, 'NE2', 'New'],
['Joe', 38, 'MC1', 'New'],
['Joe', 34, 'NE2', 'New'],
['Nick', 38, 'MC1', 'New'],
['Al', 38, 'SSE1', 'New'],
['Al', 34, 'ME', 'New'],
['Al', 34, 'MC1', 'New'],
['Joe', 43, 'S1', 'New']], columns = ['Name','Code_A','Code_B','Type'])


import seaborn as sns
sns.set(style="darkgrid")
palette ={"Classic":"#FF9999","New":"#99CC99"}


g = sns.countplot(y="Name",
palette=palette,
hue="Type",
data=test_df)

所以代替:

enter image description here

“Joe”将位于顶部,然后是“Sam”等。

最佳答案

添加order 参数。使用pandas.crosstabsort_values来获取:

import pandas as pd

test_df = pd.DataFrame([
['Jake', 38, 'MW', 'Classic'],
['John', 38,'NW', 'Classic'],
['Sam', 34, 'SE', 'Classic'],
['Sam', 22, 'E' ,'Classic'],
['Joe', 43, 'ESE2', 'Classic'],
['Joe', 34, 'MTN2', 'Classic'],
['Joe', 38, 'MTN2', 'Classic'],
['Scott', 38, 'ESE2', 'Classic'],
['Chris', 34, 'SSE1', 'Classic'],
['Joe', 43, 'S1', 'New'],
['Paul', 34, 'NE2', 'New'],
['Joe', 38, 'MC1', 'New'],
['Joe', 34, 'NE2', 'New'],
['Nick', 38, 'MC1', 'New'],
['Al', 38, 'SSE1', 'New'],
['Doug', 34, 'ME', 'New'],
['Fred', 34, 'MC1', 'New'],
['Joe', 43, 'S1', 'New']], columns = ['Name','Code_A','Code_B','Type'])


import seaborn as sns
sns.set(style="darkgrid")
palette ={"Classic":"#FF9999","New":"#99CC99"}

order = pd.crosstab(test_df.Name, test_df.Type).sort_values('Classic', ascending=False).index
g = sns.countplot(y="Name",
palette=palette,
hue="Type",
data=test_df,
order=order
)

enter image description here

关于python - Seaborn.countplot : order categories by count, 也按类别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55418807/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com