Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
707 views
in Technique[技术] by (71.8m points)

python - How to sort bars in a bar plot in ascending order?

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
df.groupby(['Id']).median().sort_values("Speed").plot.bar()

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

EDIT: so you need to do this:

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

and in sns.barplot add order:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...