Python 在 seaborn 条形图中绘制 value_counts()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31460146/
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 10:02:10  来源:igfitidea点击:

plotting value_counts() in seaborn barplot

pythonpandasseaborn

提问by AZhao

I'm having trouble getting a barplot in seaborn. Here's my reproducible data:

我无法在 seaborn 中获取条形图。这是我的可重复数据:

people = ['Hannah', 'Bethany', 'Kris', 'Alex', 'Earl', 'Lori']
reputation = ['awesome', 'cool', 'brilliant', 'meh', 'awesome', 'cool']
dictionary = dict(zip(people, reputation))
df = pd.DataFrame(dictionary.values(), dictionary.keys())
df = df.rename(columns={0:'reputation'})

Then I want to get a bar plot showing the value counts of different reputation. I've tried:

然后我想得到一个条形图,显示不同声誉的价值计数。我试过了:

sns.barplot(x = 'reputation', y = df['reputation'].value_counts(), data = df, ci = None)

and

sns.barplot(x = 'reputation', y = df['reputation'].value_counts().values, data = df, ci = None)

but both return blank plots.

但都返回空白图。

Any idea what I can do to get this?

知道我能做些什么来得到这个吗?

采纳答案by BrenBarn

In the latest seaborn, you can use the countplotfunction:

在最新的seaborn中,可以使用该countplot函数:

seaborn.countplot(x='reputation', data=df)

To do it with barplotyou'd need something like this:

要做到这一点,barplot你需要这样的东西:

seaborn.barplot(x=df.reputation.value_counts().index, y=df.reputation.value_counts())

You can't pass 'reputation'as a column name to xwhile also passing the counts in y. Passing 'reputation' for xwill use the valuesof df.reputation(all of them, not just the unique ones) as the xvalues, and seaborn has no way to align these with the counts. So you need to pass the unique values as xand the counts as y. But you need to call value_countstwice (or do some other sorting on both the unique values and the counts) to ensure they match up right.

您不能将'reputation'列名x传递给同时传递y. 过客“声誉”为x将使用df.reputation作为(所有的人,不只是那些独特)x的值,seaborn没有办法与计数对准这些。所以你需要传递唯一值 asx和计数 as y。但是您需要调用value_counts两次(或对唯一值和计数进行其他排序)以确保它们正确匹配。

回答by Jim K.

Using just countplotyou can get the bars in the same order as .value_counts()output too:

仅使用countplot您也可以按照与.value_counts()输出相同的顺序获取条形:

seaborn.countplot(data=df, x='reputation', order=df.reputation.value_counts().index)