在熊猫中使用groupby函数绘制饼图并绘图

时间:2020-10-12 17:21:55

标签: python pandas pandas-groupby pie-chart

由于函数groupby在数据帧上,我试图绘制饼图。

我能够返回 groupby函数的正确结果,但是当尝试绘制饼图时,它不会显示所有结果。

代码:

tl = pd.unique(df['event_type'].tolist())

th = pd.unique(df['event_mohafaza'].tolist())

ct = df.groupby(['event_mohafaza','event_type']).aggregate('sum')

ct = ct.reset_index()
ct['labels'] = df['event_mohafaza'] + ' ' + df['event_type']

trace = go.Pie(labels=ct['labels'], 
                hoverinfo='label+percent', 
                values=ct['number_person'], 
                textposition='outside',                
                rotation=90)
layout = go.Layout(
                   title="Percentage of events",
                   font=dict(family='Arial', size=12, color='#909090'),
                   legend=dict(x=0.9, y=0.5)
                    )
data = [trace]
fig = go.Figure(data=data, layout=layout)
fig.show()

groupby函数的结果:

                                 number_person
event_mohafaza event_type                     
loc1           swimming                9157
               football                690
               baseball                2292

loc2           swimming               10560
               football               8987
               baseball               70280
              
loc3           basketball             130
               swimming               19395
               football               5370
               baseball               19078
              
loc4           swimming               9492
               football               50
               baseball               5279

loc5           swimming               4652
               football               2215
               baseball               3000

绘制的饼图:

它没有显示所有值,必须将饼分为 16个,现在将其分为 8个

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试使用:

values = ct['number_person'].value_counts()