2017-02-10 91 views
1

我一直在試圖建立一個分組排序柱狀圖像這樣一個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

回答

0
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