【发布时间】:2020-10-14 06:44:51
【问题描述】:
我有一个运行交叉表函数的数据框,我想将交叉表绘制成饼图。
问题出在饼图中的value和label参数。
数据框:
event_type date event_mohafaza number_person groups
0 watch movie 2020-08-14 loc1 25 group1
1 stay at home 2020-08-14 loc3 32 group1
2 watch movie 2020-08-14 loc2 45 group2
3 swimming 2020-08-14 loc4 12 group1
4 stay at home 2020-08-14 loc2 45 group3
5 watch movie 2019-06-14 loc5 22 group1
6 watch movie 2020-08-14 loc2 10 group4
7 watch movie 2020-08-14 loc1 44 group1
8 stay at home 2020-08-14 loc3 22 group3
9 swimming 2020-08-14 loc2 32 group2
10 watch movie 2019-09-14 loc1 17 group1
11 camping 2020-08-14 loc4 27 group1
12 watch movie 2020-08-14 loc5 43 group3
13 meeting 2019-06-14 loc2 33 group2
14 camping 2020-08-14 loc1 21 group4
交叉表:
event_type camping camping meeting stay at home \
year_month
2019/06 0 0 1 0
2019/09 0 0 0 0
2020/08 1 1 0 3
event_type swimming swimming watch movie
year_month
2019/06 0 0 1
2019/09 0 0 1
2020/08 1 1 5
饼图绘制:
ddf['year_month'] = ddf['date'].map(lambda x: x.strftime('%Y/%m'))
ct = pd.crosstab(ddf['year_month'], ddf['event_type'])
print(ct)
ct = ct.reset_index()
ct['labels'] = ct['year_month'] + ' ' + ct['event_type']
trace = go.Pie(labels=ct['labels'],
hoverinfo='label+percent',
values=ct['event_type'],
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]
print(data)
fig = go.Figure(data=data, layout=layout)
fig.show()
【问题讨论】:
标签: python pandas plotly pie-chart crosstab