簡體   English   中英

使用pandas創建分組排序的條形圖

[英]Creating a grouped sorted bar plot using pandas

我一直在嘗試創建一個分組排序的條形圖,例如這個來自從dict創建的DataFrame中的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   

第一組應該有蘋果和漿果,第二組應該有黃油和奶酪牛奶到底。 到目前為止,上面沒有將條形分開(見圖)。 我怎樣才能做到這一點以及對每組中的酒吧進行排序?

圖表

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

情節結果

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM