pandas 带 groupby 的条形图

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

Bar plot with groupby

pandasmatplotlibseaborn

提问by jacob

My categorical variable case_satustakes on four unique values. I have data from 2014 to 2016. I would like to plot the distribution of case_statusgrouped by year. I try to this using:

我的分类变量case_satus具有四个唯一值。我有 2014 年到 2016 年的数据。我想绘制case_status按年份分组的分布。我尝试使用:

df.groupby('year').case_status.value_counts().plot.barh()

And I get the following plot:

我得到以下情节:

output

输出

What I would like to have is a nicer represenation. For example where I have one color for each year, and all the "DENIED" would stand next to each other.

我想要的是一个更好的代表。例如,我每年有一种颜色,所有“拒绝”都会彼此相邻。

I think it can be achieved since the groupby object is a multi-index, but I don't understand it well enough to create the plot I want.

我认为它可以实现,因为 groupby 对象是一个多索引,但我对它的理解不够好,无法创建我想要的图。



The solution is:

解决办法是:

df.groupby('year').case_status.value_counts().unstack(0).plot.barh()

and results in

并导致

enter image description here

在此处输入图片说明

回答by jezrael

I think you need add unstackfor DataFrame:

我认为你需要添加unstackDataFrame

df.groupby('year').case_status.value_counts().unstack().plot.barh()

Also is possible change level:

也是可能的更改级别:

df.groupby('year').case_status.value_counts().unstack(0).plot.barh()