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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:44:17  来源:igfitidea点击:

Seaborn.countplot : order categories by count?

pythonpandasplotseaborn

提问by nfernand

I know that seaborn.countplothas the attribute orderwhich 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 groupbyoperation 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.countplotas far as I know - the orderparameter 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()

enter image description here

在此处输入图片说明

回答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()