Based on https://stackoverflow.com/questions/44885933/how-to-sort-bars-in-a-bar-plot-in-ascending-order .
Works in notebooks launched from here.
#%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
#"For examples that use the StringIO class, make sure you import it according to your Python version, i.e. from StringIO import StringIO for Python 2 and from io import StringIO for Python 3." - http://pandas.pydata.org/pandas-docs/stable/io.html
#from StringIO import StringIO # see http://pandas.pydata.org/pandas-docs/stable/io.html
from io import StringIO # see http://pandas.pydata.org/pandas-docs/stable/io.html
input ='''
Id Speed
1 30
1 35
1 31
2 20
2 25
3 80
'''
df = pd.read_table(StringIO(input), header=0, index_col=None, delim_whitespace=True)
print(df.head())
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"])) # was causing issues when not at tmpnb.org
# and I didn't want to specify a Seaborn only palette, so just let go to default now
plt.figure(figsize=(12,8))
sns.barplot(x="Id", y="Speed", data=df) # formerly: sns.barplot(x="Id", y="Speed", data=df, palette=colors)
plt.ylabel('Speed', fontsize=12)
plt.xlabel('Id', fontsize=12)
plt.xticks(rotation='vertical')
plt.show()
Id Speed 0 1 30 1 1 35 2 1 31 3 2 20 4 2 25
result = df.groupby(["Id"])['Speed'].aggregate(np.median).reset_index().sort_values('Speed')
sns.barplot(x='Id', y="Speed", data=df, order=result['Id']) #formerly: sns.barplot(x='Id', y="Speed", data=df, palette=colors, order=result['Id'])
plt.show()
result
Id | Speed | |
---|---|---|
1 | 2 | 22.5 |
0 | 1 | 31.0 |
2 | 3 | 80.0 |