pandas 如何在条形图中按递增顺序对条形进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47137909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort bars in increasing order in a bar chart?
提问by Dinosaurius
I have a DataFrame df
that I convert to df_c
using the code shown below:
我有一个 DataFrame df
,我可以df_c
使用下面显示的代码将其转换为:
df = pd.DataFrame(columns=["App","Feature1", "Feature2","Feature3",
"Feature4","Feature5",
"Feature6","Feature7","Feature8"],
data=[["SHA",0,0,1,1,1,0,1,0],
["LHA",1,0,1,1,0,1,1,0],
["DRA",0,0,0,0,0,0,1,0],
["FRA",1,0,1,1,1,0,1,1],
["BRU",0,0,1,0,1,0,0,0],
["PAR",0,1,1,1,1,0,1,0],
["AER",0,0,1,1,0,1,1,0],
["SHE",0,0,0,1,0,0,1,0]])
df_c = df.iloc[:, 1:].eq(1).sum().rename_axis('Feature').reset_index(name='Cou??nt')
Then I create a bar chart using matplotlib and seaborn:
然后我使用 matplotlib 和 seaborn 创建一个条形图:
plt.figure(figsize=(12,8))
ax = sns.barplot(x="Feature", y="Count", data=df_c, palette=sns.color_palette("GnBu", 10), order=df_c['Feature'])
plt.xticks(rotation='vertical')
ax.grid(b=True, which='major', color='#d3d3d3', linewidth=1.0)
ax.grid(b=True, which='minor', color='#d3d3d3', linewidth=0.5)
plt.show()
I want to sort bars in increasing order from left to right. If I do order=df_c['Count']
, the bars disappear.
我想从左到右按递增顺序对条形进行排序。如果我这样做order=df_c['Count']
,条形就会消失。
回答by jezrael
Simplest way is to sort before plotting:
最简单的方法是在绘图之前进行排序:
df_c = df_c.sort_values('Count')