[英]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.