pandas 在熊猫中制作堆叠条形图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26683654/
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
making a stacked barchart in pandas
提问by user308827
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
There would be 2 bars in the plot. One for RECL_LCCand other for RECL_PI. There would be 3 sections in each bar corresponding to the unique values in RECL_LCCand RECL_PIi.e 1,2,3 and would sum up the COUNTfor each section. So far, I have something like this:
图中将有 2 个条。一个为RECL_LCC,另一个为RECL_PI。每个条形中将有 3 个部分,对应于RECL_LCC和 中的唯一值,RECL_PI即 1、2、3,并将总结COUNT每个部分的 。到目前为止,我有这样的事情:
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:

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

Any idea on how to fix it? I am doing something wrong with the groupby, but not sure of the solution
关于如何修复它的任何想法?我做错了groupby,但不确定解决方案
回答by Simon
I've put data shown in stackpandas.dat. Given those data:
我已经把数据显示在stackpandas.dat. 鉴于这些数据:
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()
... gives:

...给出:

... which I think is what is sought.
......我认为这就是所寻求的。

