使用pandas创建分组排序条形图

kx7yvsdv  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(91)

我一直在尝试创建一个分组排序的条形图,如这一个http://chrisalbon.com/python/matplotlib_grouped_bar_plot.html从一个DataFrame创建从dict通过这样做:

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

字符串
第一组应该有苹果和浆果,第二组应该有黄油和奶酪牛奶到最后。到目前为止,上面没有分开的酒吧(见图)。我怎么才能做到这一点,以及排序酒吧在每一组?


的数据

zd287kbt

zd287kbt1#

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)

字符串
输出如下:

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


的数据

相关问题