在大 pandas 中制作堆积的条形图 [英] making a stacked barchart in pandas

查看:85
本文介绍了在大 pandas 中制作堆积的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从以下数据框中创建一个堆积的条形图:

I would like to create a stacked bar plot from the following dataframe:

   VALUE     COUNT  RECL_LCC  RECL_PI
0      1  15686114         3        1
1      2  27537963         1        1
2      3  23448904         1        2
3      4   1213184         1        3
4      5  14185448         3        2
5      6  13064600         3        3
6      7  27043180         2        2
7      8  11732405         2        1
8      9  14773871         2        3

图中将有2条.一个用于RECL_LCC,另一个用于RECL_PI.每个栏中将有3个部分与RECL_LCCRECL_PI中的唯一值相对应,即1,2,3,并将每个部分的COUNT求和.到目前为止,我有这样的事情:

There would be 2 bars in the plot. One for RECL_LCC and other for RECL_PI. There would be 3 sections in each bar corresponding to the unique values in RECL_LCC and RECL_PI i.e 1,2,3 and would sum up the COUNT for each section. So far, I have something like this:

df = df.convert_objects(convert_numeric=True)    
sub_df = df.groupby(['RECL_LCC','RECL_PI'])['COUNT'].sum().unstack()
sub_df.plot(kind='bar',stacked=True)

但是,我得到了这个情节:

However, I get this plot:

关于如何解决它的任何想法? groupby我做错了,但不确定解决方案

Any idea on how to fix it? I am doing something wrong with the groupby, but not sure of the solution

推荐答案

我将数据显示在stackpandas.dat中.鉴于这些数据:

I've put data shown in stackpandas.dat. Given those data:

from pandas import *
import matplotlib.pyplot as plt

df = read_table("stackpandas.dat"," +",engine='python')

df = df.convert_objects(convert_numeric=True)
sub_df1 = df.groupby(['RECL_LCC'])['COUNT'].sum()
sub_df2 = df.groupby(['RECL_PI'])['COUNT'].sum()
sub_df = concat([sub_df1,sub_df2],keys=["RECL_LCC","RECL_PI"]).unstack()
sub_df.plot(kind='bar',stacked=True,rot=1)
plt.show()

...给出:

...我想是要寻求的.

... which I think is what is sought.

这篇关于在大 pandas 中制作堆积的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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