Python - 使用pivot table pandas数据框创建柱状图

2024-05-28 19:04:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,想知道如何在使用pivot table函数创建的数据上创建一个barplot。

#Create a pivot table for handicaps count calculation for no-show people based on their gender 
pv = pd.pivot_table(df_main, values=['hipertension','diabetes','alcoholism'], 
                     columns='status',index='gender',aggfunc=np.sum)
#Reshape the pivot table for easier calculation 

data_pv = pv.unstack().unstack('status').reset_index().rename(columns={'level_0':'category','No-Show':'no_show', 'Show-Up':'show_up'})

data_pv['no_show_prop'] = (data_pv['no_show']/
                          (data_pv['no_show']+data_pv['show_up']))*100
data_pv

因此:

status  category    gender  no_show show_up no_show_prop
0   alcoholism      F        308       915     25.183974
1   alcoholism      M        369      1768     17.267197
2   diabetes        F        1017     4589     18.141277
3   diabetes        M        413      1924     17.672229
4   hipertension    F        2657    12682     17.321859
5   hipertension    M        1115     5347     17.254720

我想创建一个条形图,其中类别为x轴,没有显示为y轴,每个类别有两个不同颜色的条形图表示女性和男性。我也尝试过使用groupby,但它并不像我想的那样出现。

Instead of bar like in this picture below, I want to create a bar graph with category as x-axis and no_show_prop as y-axis with two different colors bars indicate female and male for each category. I also tried using groupby but it's not come out as I wanted to be.


Tags: nofordatastatusshowtablegenderpivot
2条回答

对于这样的任务,您也可以使用seaborn,这使得从DataFrame生成分类条形图变得非常容易

import seaborn as sns

sns.barplot(x='category', y='no_show_prop', hue='gender', data=df)

enter image description here

我想这应该符合你的要求。从当前的data_pv开始,您可以执行以下操作,将数据重塑为更易于按所需方式绘制的表单。

df = data_pv.pivot(index='category', columns='gender', values='no_show_prop')

df现在看起来像:

gender                F          M
category                          
alcoholism    25.183974  17.267197
diabetes      18.141277  17.672229
hipertension  17.321859  17.254720

然后你可以简单地:

df.plot(kind='bar')

enter image description here

相关问题 更多 >

    热门问题