2017-07-03 981 views
1

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

回答更新。 –

回答

3
df.groupby(['Id']).median().sort_values("Speed").plot.bar() 

或者只是尝试sort_values( “速度”)您汇总后他们。

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

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']) 
+0

谢谢。我尝试了这种方法,但酒吧没有排序。如果我在聚合后添加'sort_values',那么我得到这个错误:'ValueError:没有名为速度的对象类型' – Dinosaurius

+0

现在它工作。谢谢。 – Dinosaurius

+0

我做了一个笔记本,原始的和排序的结果都显示在一起[这里](https://nbviewer.jupyter.org/gist/fomightez/bb5a9c727d93d1508187677b4d74d7c1)。 – Wayne

相关问题