Seaborn.countplot:按计数排序类别? [英] Seaborn.countplot : order categories by count?
问题描述
我知道 seaborn.countplot
具有属性order
,该属性可以设置以确定类别的顺序.但是我想做的是按降序排列类别.我知道我可以通过手动计算计数(在原始数据帧上使用groupby
操作等)来完成此操作,但是我想知道seaborn.countplot
是否存在此功能.令人惊讶的是,我在任何地方都找不到这个问题的答案.
I know that seaborn.countplot
has the attribute order
which can be set to determine the order of the categories. But what I would like to do is have the categories be in order of descending count. I know that I can accomplish this by computing the count manually (using a groupby
operation on the original dataframe, etc.) but I am wondering if this functionality exists with seaborn.countplot
. Surprisingly, I cannot find an answer to this question anywhere.
推荐答案
据我所知,此功能未内置在seaborn.countplot
中-order
参数仅接受类别字符串的列表,并保留用户的订购逻辑.
This functionality is not built into seaborn.countplot
as far as I know - the order
parameter only accepts a list of strings for the categories, and leaves the ordering logic to the user.
使用 value_counts()
并不难,但前提是您有一个DataFrame.例如
This is not hard to do with value_counts()
provided you have a DataFrame though. For example,
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style='darkgrid')
titanic = sns.load_dataset('titanic')
sns.countplot(x = 'class',
data = titanic,
order = titanic['class'].value_counts().index)
plt.show()
这篇关于Seaborn.countplot:按计数排序类别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!