【问题标题】:How to sort bars in a bar plot in ascending order如何按升序对条形图中的条形进行排序
【发布时间】:2017-12-06 17:51:06
【问题描述】:

我使用 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()

【问题讨论】:

    标签: python pandas matplotlib seaborn


    【解决方案1】:
    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'])
    

    【讨论】:

      猜你喜欢
      • 2018-04-18
      • 1970-01-01
      • 2014-10-02
      • 2021-07-06
      • 2022-08-23
      • 2020-09-01
      • 2014-05-03
      • 2018-12-21
      • 2021-10-10
      相关资源
      最近更新 更多