python - 将交叉表 pandas 绘制成饼图
问题描述
我有一个运行交叉表函数的数据框,我想将交叉表绘制成饼图。
问题在于饼图中的值和标签参数。
数据框:
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()
解决方案
您可以以垂直格式绘制图形,而无需将数据框更改为水平格式。代码格式已根据官方参考进行了改写。这个答案是你打算做的吗?
ddf['date'] = pd.to_datetime(ddf['date'])
ddf['year_month'] = ddf['date'].map(lambda x: x.strftime('%Y/%m'))
ddf['labels'] = ddf['year_month'] + ' ' + ddf['event_type']
import plotly.graph_objects as go
fig = go.Figure(data=[go.Pie(labels=ddf['labels'],
hoverinfo='label+percent',
values=ddf['number_person'],
textposition='outside',
rotation=90)])
fig.update_layout(title="Percentage of events",
font=dict(family='Arial', size=12, color='#909090'),
legend=dict(x=0.9, y=0.5)
)
fig.show()
推荐阅读
- javascript - 参数被重新分配
- android - 如何解决此 Logcat 错误
- r - Spark JDBC 连接到 SQL Server 经常超时
- ruby - 从 Packetbeat 解码 gzip 响应正文
- python - 这是什么意思?DeprecationWarning:调用已弃用的函数 get_sheet_by_name(使用 wb[sheetname])
- php - Find string which changes it position in URL
- c# - 为什么 Vector3 必须公开或序列化才能从另一个脚本设置它的值
- java - 我应该如何处理 OOP 中的基本功能?
- node.js - 使用对等依赖和本地(文件:../some-lib)依赖
- python - Django 表单未在 html 模板中显示