使用 pandas 创建分组的排序条形图 [英] Creating a grouped sorted bar plot using pandas
本文介绍了使用 pandas 创建分组的排序条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试创建一个分组的排序条形图,例如一个
解决方案
将熊猫作为pd导入#您的数据食物= {苹果作为水果":4.68,浆果":7.71,黄油":12.73,\奶酪":4.11,乳制品,其他":4.97}dframe = pd.DataFrame([food])#进行一些调整dframe = dframe.Tdframe.index.names = ['name']#添加一个索引'group'dframe ['group'] = ['fruit','fruit','other','other','other']dframe.set_index('group',inplace = True,append = True)#取消堆叠dframe = dframe [0] .unstack(level ='group').fillna(0)#排序值dframe.sort_values(by = dframe.columns.tolist(),inplace = True,ascending = False)打印(dframe)# 阴谋dframe.plot(kind ='bar',width = 2)
输出如下:
组水果其他名称浆果7.71 0.00苹果为水果4.68 0.00黄油0.00 12.73乳制品,其他0.00 4.97芝士0.00 4.11
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:
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
这篇关于使用 pandas 创建分组的排序条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文