#!/usr/bin/env python # coding: utf-8 # # Unsorted and after Sorting Pandas with plot example # # Based on https://stackoverflow.com/questions/44885933/how-to-sort-bars-in-a-bar-plot-in-ascending-order . # # Works in notebooks launched from [here](https://github.com/fomightez/vpython-jupyter). # In[1]: #%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 ''' # ## First the unsorted example # In[2]: 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() # ## The Result Sorted by Speed # In[3]: 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() # In[4]: result # In[ ]: