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
plotting value_counts() in seaborn barplot
提问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 countplot
function:
在最新的seaborn中,可以使用该countplot
函数:
seaborn.countplot(x='reputation', data=df)
To do it with barplot
you'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 x
while also passing the counts in y
. Passing 'reputation' for x
will use the valuesof df.reputation
(all of them, not just the unique ones) as the x
values, and seaborn has no way to align these with the counts. So you need to pass the unique values as x
and the counts as y
. But you need to call value_counts
twice (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 countplot
you 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)