使用groupby创建百分比堆积的条形图 [英] Creating percentage stacked bar chart using groupby

查看:86
本文介绍了使用groupby创建百分比堆积的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看处于不同贷款状态级别的房屋所有权,我想使用堆积的条形图以百分比形式显示此信息.

我已经可以使用以下代码创建频率堆叠的条形图:

  df_trunc1 = df [['loan_status','home_ownership','id']]sub_df1 = df_trunc1.groupby(['loan_status','home_ownership'])['id'].count()sub_df1.unstack().plot(种类='bar',stacked = True,rot = 1,figsize =(8,8),title =所有贷款类型的房屋所有权") 

这给了我这张照片:

  sub_df3 = sub_df1.unstack().Tsub_df3.index = sub_df3.index.droplevel()#删除`count`标签.sub_df3 = sub_df3.div(sub_df3.sum())sub_df3.T.plot(种类='bar',堆叠=真,腐烂= 1,图大小=(8,8),title =所有贷款类型的房屋所有权") 

I'm looking at home ownership within levels of different loan statuses, and I'd like to display this using a stacked bar chart in percentages.

I've been able to create a frequency stacked bar chart using this code:

df_trunc1=df[['loan_status','home_ownership','id']]
sub_df1=df_trunc1.groupby(['loan_status','home_ownership'])['id'].count()
sub_df1.unstack().plot(kind='bar',stacked=True,rot=1,figsize=(8,8),title="Home ownership across Loan Types")

which gives me this picture:1

but I can't figure out how to transform the graph into percentages. So for example, I'd like to get within the default group, which percentage have a mortgage, which own, etc.

Here is my groupby table for context2:

Thanks!!

解决方案

I believe you need to convert the percentages yourself:

d = {('Default', 'MORTGAGE'): 498, ('Default', 'OWN'): 110, ('Default', 'RENT'): 611, ('Fully Paid', 'MORTGAGE'): 3100, ('Fully Paid', 'NONE'): 1, ('Fully Paid', 'OTHER'): 5, ('Fully Paid', 'OWN'): 558, ('Fully Paid', 'RENT'): 2568, ('Late (16-30 days)', 'MORTGAGE'): 1101, ('Late (16-30 days)', 'OWN'): 260, ('Late (16-30 days)', 'RENT'): 996, ('Late (31-120 days)', 'MORTGAGE'): 994, ('Late (31-120 days)', 'OWN'): 243, ('Late (31-120 days)', 'RENT'): 1081}

sub_df1 = pd.DataFrame(d.values(), columns=['count'], index=pd.MultiIndex.from_tuples(d.keys()))
sub_df2 = sub_df1.unstack()
sub_df2.columns = sub_df2.columns.droplevel()  # Drop `count` label.
sub_df2 = sub_df2.div(sub_df2.sum())
sub_df2.T.plot(kind='bar', stacked=True, rot=1, figsize=(8, 8), 
               title="Home ownership across Loan Types")

sub_df3 = sub_df1.unstack().T
sub_df3.index = sub_df3.index.droplevel()  # Drop `count` label.
sub_df3 = sub_df3.div(sub_df3.sum())
sub_df3.T.plot(kind='bar', stacked=True, rot=1, figsize=(8, 8), 
               title="Home ownership across Loan Types")

这篇关于使用groupby创建百分比堆积的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆