繁体   English   中英

如何通过在 python 中使用 Plotly plot 在数据集中使用四列饼图

[英]How to plot a pie chart with four column in the dataset by using Plotly in python

数据集:

Year      ,    Store_type   ,      MY_SHOPPING         ,TRAN_SPEND
2012,      LARGE_STORE  ,         HEALTH CONSCIOUS  ,    49383.70$
2012  ,   CONVENIENCE_STORE  ,   CONFIDENT COOKS      ,  13150.00$
2013  , LARGER_STORE        ,   QUICK&EASY        ,  98765.00$
2013  , LARGER_STORE      ,    TRADITIONAL        ,  45734.00$

问题:我想要一个饼图,它代表图表中间的年份,并有一个 label = store_type 并在 MY_SHOPPING 列中显示不同类别的百分比加上该名称的名称以及以美元为单位的 TRAN_SPEND 金额

在此处输入图像描述 .

我的代码:

fig = px.pie(removed_index_storeformat, values='TRAN_SPEND', names='STORE_TYPE',
             hover_data=['MY_SHOPPING '], labels={'MY_SHOPPING ':'shop'})

fig.update_traces(textposition='inside', textinfo='percent+label')
fig.show()

甜甜圈饼图可以通过设置孔大小来实现。 此外,使用注释将文本字符串放置在添加数字列中,该列与显示的数据中标有美元符号的字符串列分开。 使用饼图的数字列和文本的原始美元标记列。

import pandas as pd
import numpy as np
import io

data = '''
Year,Store_type,MY_SHOPPING,TRAN_SPEND
2012,LARGE_STORE,HEALTH CONSCIOUS,49383.70$
2012,CONVENIENCE_STORE,CONFIDENT COOKS,13150.00$
2013,LARGER_STORE,QUICK&EASY,98765.00$
2013,LARGER_STORE,TRADITIONAL,45734.00$
'''

df = pd.read_csv(io.StringIO(data), sep=',')

df['TRAN_SPEND2'] = df['TRAN_SPEND'].apply(lambda x: float(x[:-1]))
df

    Year    Store_type  MY_SHOPPING     TRAN_SPEND  TRAN_SPEND2
0   2012    LARGE_STORE     HEALTH CONSCIOUS    49383.70$   49383.7
1   2012    CONVENIENCE_STORE   CONFIDENT COOKS     13150.00$   13150.0
2   2013    LARGER_STORE    QUICK&EASY  98765.00$   98765.0
3   2013    LARGER_STORE    TRADITIONAL     45734.00$   45734.0


import plotly.express as px

dff = df.query('Year == 2012')
fig = px.pie(dff, values='TRAN_SPEND2', names='Store_type',
             hover_data=['MY_SHOPPING'], labels={'MY_SHOPPING ':'shop'}, hole=0.3)

fig.update_traces(textposition='inside', text=dff['TRAN_SPEND'], textinfo='percent+label+text')

fig.update_layout(
    title_text="Test Title",
    annotations=[dict(text='2012', x=0.5, y=0.5, font_size=20, showarrow=False)])

fig.show()

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM