如何按升序对条形图中的条进行排序? [英] How to sort bars in a bar plot in ascending order?

查看:104
本文介绍了如何按升序对条形图中的条进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用matplotlib.pyplot和seaborn库创建了一个条形图.如何根据Speed以递增顺序对条形进行排序?我想看到速度最低的条在左侧,速度最高的条在右侧.

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.

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")进行排序.

Or just try to sort_values("Speed") after you aggregate them.

所以您需要这样做:

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

并在sns.barplot中添加顺序:

and in sns.barplot add order:

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

这篇关于如何按升序对条形图中的条进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆