如何按升序对条形图中的条形进行排序

How to sort bars in a bar plot in ascending order

我使用 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()
df.groupby(['Id']).median().sort_values("Speed").plot.bar()

聚合后使用 .sort_values("Speed").sort_values('Speed', ascending=False) 对数据框进行排序。

编辑: 所以你需要这样做:

result = a.groupby(["Id"])['Speed'].median().reset_index().sort_values('Speed')

并在 sns.barplot 添加顺序:

sns.barplot(x='Id', y="Speed", data=a, palette=colors, order=result['Id'])