我使用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()
答案 0 :(得分:6)
df.groupby(['Id']).median().sort_values("Speed").plot.bar()
或者只是在聚合后尝试sort_values(" Speed")。
编辑: 所以你需要这样做:
result = a.groupby(["Id"])['Speed'].aggregate(np.median).reset_index().sort_values('Speed')
并在sns.barplot中添加顺序:
sns.barplot(x='Id', y="Speed", data=a, palette=colors, order=result['Id'])