简体   繁体   English

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

[英]Creating a grouped sorted bar plot using pandas

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: 我一直在尝试创建一个分组排序的条形图,例如这个来自从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   

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? 我怎样才能做到这一点以及对每组中的酒吧进行排序?

图表

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 情节结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM