Python 如何按升序对条形图中的条形进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44885933/
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 a bar plot in ascending order?
提问by Dinosaurius
I created a bar plot using matplotlib.pyplot and seaborn libraries. How can I sort bars in increasing order according to Speed
? I want to see the bars with the lowest speed on the left and the highest speed on the right.
我使用 matplotlib.pyplot 和 seaborn 库创建了一个条形图。如何根据 以递增顺序对条形进行排序Speed
?我想在左边看到速度最低的条形,在右边看到速度最快的条形。
df =
Id Speed
1 30
1 35
1 31
2 20
2 25
3 80
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
result = df.groupby(["Id"])['Speed'].aggregate(np.median).reset_index()
norm = plt.Normalize(df["Speed"].values.min(), df["Speed"].values.max())
colors = plt.cm.Reds(norm(df["Speed"]))
plt.figure(figsize=(12,8))
sns.barplot(x="Id", y="Speed", data=gr_vel_1, palette=colors)
plt.ylabel('Speed', fontsize=12)
plt.xlabel('Id', fontsize=12)
plt.xticks(rotation='vertical')
plt.show()
回答by Kacper Wolkowski
df.groupby(['Id']).median().sort_values("Speed").plot.bar()
Or just try to sort_values("Speed") after you aggregate them.
或者在聚合它们后尝试 sort_values("Speed") 。
EDIT: so you need to do this:
编辑:所以你需要这样做:
result = a.groupby(["Id"])['Speed'].aggregate(np.median).reset_index().sort_values('Speed')
and in sns.barplot add order:
并在 sns.barplot 添加顺序:
sns.barplot(x='Id', y="Speed", data=a, palette=colors, order=result['Id'])