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

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

问题描述

我使用matplotlib.pyplot和海运库创建了条形图。如何根据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.barlot中添加顺序:

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

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

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