[英]How to sort bars in a bar plot in ascending order?
I created a bar plot using matplotlib.pyplot and seaborn libraries. 我使用matplotlib.pyplot和seaborn库创建了一个条形图。 How can I sort bars in increasing order according to
Speed
? 如何根据
Speed
按升序排序条形图? I want to see the bars with the lowest speed on the left and the highest speed on the right. 我想看到左边最低速度的条和右边最高速度的条。
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()
df.groupby(['Id']).median().sort_values("Speed").plot.bar()
Or just try to sort_values("Speed") after you aggregate them. 或者只是在聚合后尝试sort_values(“速度”)。
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'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.