0

I am trying to sort the columns in seaborn catplot and I am unable to perform this operation. I know I can sort the bars within the graph using order= but how to sort the columns? So far, I have written this code for plotting:

top_codes = df["Code"].value_counts()[:5].index.tolist()
top_stations = df["Station"].value_counts()[:5].index.tolist()
sns.catplot(x='Code',col='Station', data=df.loc[(df['Code'].isin(top_codes)) & (df['Station'].isin(top_stations))],
            kind='count', col_wrap=5)

The above code produces the following result: enter image description here

I want station names, e.g., KENNEDY BD STATION, SHEPPHARD WEST STATION, FINCH STATION to appear in alphabetical order.

raziiq
  • 115
  • 3
  • Perhaps change `df.loc[(df['Code'].isin(top_codes)) & (df['Station'].isin(top_stations))` to `df.loc[(df['Code'].isin(top_codes)) & (df['Station'].isin(top_stations)).sort_values(by="Station")` in the plot code. – Rawson May 20 '22 at 18:35
  • `df.Station = pd.Categorical(df.Station, sorted(df.Station.unique()), ordered=True)` [code and plot](https://i.stack.imgur.com/d4p0S.png) – Trenton McKinney May 20 '22 at 19:22

1 Answers1

0

A simple ascending sort is very easy: just call the sorted() function. Add code_order=sorted(top_stations) as parameter to sns.catplot like this:

top_codes = df["Code"].value_counts()[:5].index.tolist()
top_stations = df["Station"].value_counts()[:5].index.tolist()
sns.catplot(x='Code',col='Station', data=df.loc[(df['Code'].isin(top_codes)) & (df['Station'].isin(top_stations))],
        kind='count', col_wrap=5, code_order=sorted(top_stations))
allabur
  • 38
  • 3