Python 用熊猫制作堆叠条形图
我想从以下数据框创建堆叠条形图:Python 用熊猫制作堆叠条形图,python,pandas,plot,bar-chart,stacked,Python,Pandas,Plot,Bar Chart,Stacked,我想从以下数据框创建堆叠条形图: 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
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
图中会有两条线。一个用于RECL\u LCC
,另一个用于RECL\u PI
。每个条中有3个部分对应于RECL_LCC
和RECL_PI
中的唯一值,即1,2,3,并将每个部分的计数相加。到目前为止,我有这样的想法:
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)
然而,我得到了这样的情节:
你知道怎么修吗?我对groupby
做了一些错误,但不确定解决方案我已经将数据放在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()
。。。给予:
。。。我认为这正是我所追求的。我正在与类似的问题作斗争。请帮忙好吗?