Python Seaborn.countplot:按计数排序类别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46623583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Seaborn.countplot : order categories by count?
提问by nfernand
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
可以设置来确定类别顺序的属性。但我想做的是让类别按降序排列。我知道我可以通过手动计算计数来实现这一点(使用groupby
对原始数据帧的操作等),但我想知道这个功能是否存在于seaborn.countplot
. 令人惊讶的是,我在任何地方都找不到这个问题的答案。
回答by miradulo
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.
seaborn.countplot
据我所知,此功能并未内置- 该order
参数仅接受类别的字符串列表,并将排序逻辑留给用户。
This is not hard to do with value_counts()
provided you have a DataFrame though. For example,
value_counts()
如果你有一个 DataFrame,这并不难。例如,
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()
回答by ImportanceOfBeingErnest
Most often, a seaborn countplot is not really necessary. Just plot with pandas bar plot:
大多数情况下,seaborn 计数图并不是真正必要的。只需绘制熊猫条形图:
import seaborn as sns; sns.set(style='darkgrid')
import matplotlib.pyplot as plt
df = sns.load_dataset('titanic')
df['class'].value_counts().plot(kind="bar")
plt.show()