Python: Creating bar plot from pivot table pandas data frame

心不动则不痛 提交于 2021-02-16 05:31:09

问题


I'm new to python and was wondering how to create a barplot on this data I created using pivot table function.

#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

And as a result:

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

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.

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.


回答1:


I think this should do what you're looking for. Starting with your current data_pv, you can do the following to reshape the data into a form that's easier to plot in the way that you want.

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

df now looks like:

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

Then you can simply do:

df.plot(kind='bar')




回答2:


For a task like this you can also just use seaborn, which makes it very easy to make a categorized barplot from a DataFrame

import seaborn as sns

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



来源:https://stackoverflow.com/questions/50396479/python-creating-bar-plot-from-pivot-table-pandas-data-frame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!