Creating a grouped sorted bar plot using pandas

◇◆丶佛笑我妖孽 提交于 2021-02-11 09:39:45

问题


I have been trying to create a grouped sorted bar plot such as this one http://chrisalbon.com/python/matplotlib_grouped_bar_plot.html from a DataFrame created from dict by doing:

food = {'Apples as fruit': 4.68, 'Berries': 7.71, 'Butter': 12.73, 
              'Cheese': 4.11, 'Dairy, Other': 4.97}

dframe = pd.DataFrame([food])
dframe.plot(kind='bar')

    Apples as fruit  Berries     Butter    Cheese    Dairy, Other   
0   4.68             7.71        12.73     4.11      4.97   

The first group should have Apples and Berries and the second should have Butter and Cheese milk to the end. So far the above does not separate the bars(see image). How can I go about doing this as well as sorting the bars in each group?


回答1:


import pandas as pd

# your data 

food = {'Apples as fruit': 4.68, 'Berries': 7.71, 'Butter': 12.73, \
              'Cheese': 4.11, 'Dairy, Other': 4.97}

dframe = pd.DataFrame([food])

#make some adjustment

dframe = dframe.T
dframe.index.names = ['name']

# add an index 'group' 

dframe['group'] = ['fruit', 'fruit', 'other', 'other', 'other']
dframe.set_index('group', inplace=True, append=True)

# unstack

dframe = dframe[0].unstack(level='group').fillna(0)

# sort values

dframe.sort_values(by=dframe.columns.tolist(), inplace=True, ascending=False)

print(dframe) 

# plot

dframe.plot(kind='bar', width=2)

the output is like below:

   group            fruit  other
name                         
Berries           7.71   0.00
Apples as fruit   4.68   0.00
Butter            0.00  12.73
Dairy, Other      0.00   4.97
Cheese            0.00   4.11

plot result



来源:https://stackoverflow.com/questions/42151637/creating-a-grouped-sorted-bar-plot-using-pandas

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