做创建使用熊猫

问题描述:

我一直在试图建立一个分组排序柱状图像这样一个http://chrisalbon.com/python/matplotlib_grouped_bar_plot.html从字典中创建一个数据帧一个分组排序条形图:做创建使用熊猫

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 

第一组应该有苹果和浆果和第二个应该有黄油和奶酪牛奶到最后。到目前为止,上述不会分隔条(见图)。我怎么能做到这一点,以及在每个组中排序吧?

chart

+0

所以,如果我理解正确:你想两组吧:在与酒吧的苹果作为水果和浆果彼此相邻,其他所有其他类型?你能提供一个你喜欢它的样子吗? – Chuck

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 

plot result