Python:从数据透视表pandas数据框创建条形图

时间:2018-05-17 16:35:17

标签: python pandas matplotlib pivot-table

我是python的新手,想知道如何在我使用数据透视表函数创建的数据上创建一个条形图。

#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轴,no_show_prop为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.

2 个答案:

答案 0 :(得分:2)

我认为这应该做你正在寻找的事情。从您当前的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

答案 1 :(得分:1)

对于这样的任务,您也可以使用seaborn,这样可以很容易地从DataFrame

制作分类条形图
import seaborn as sns

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

enter image description here