Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:从数据帧透视表创建条形图_Python_Pandas_Matplotlib_Pivot Table - Fatal编程技术网

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

Python:从数据帧透视表创建条形图,python,pandas,matplotlib,pivot-table,Python,Pandas,Matplotlib,Pivot Table,我是python新手,想知道如何在我使用pivot表函数创建的数据上创建条形图 #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='statu

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

#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,但结果不是我想要的


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

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')

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

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')

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


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