How to sort the columns of a Seaborn Heatmap using custom order?

Viewed 1323

I want to sort the columns of this heatmap by the average of each column ascending from left to right (so here Boston Celtics would be the left most column, etc). It seems the default x-axis sort order is alphabetical. I've read some similar questions but none of them quite helped me figure this out.

enter image description here

1 Answers

You can just reorder the dataframe using reindex before feeding it into sns.heatmap.

For example:

import numpy as np
import pandas as pd
import seaborn as sns

np.random.seed(999)

df = pd.DataFrame(np.random.uniform(0,1,(7,4)),
                  index=np.arange(2014,2021),
                  columns = ['Atalanta Hawks','Boston Celtics',
                             'Cleveland Cavaliers','Denver Nuggets']
                 )

Desired order:

df.mean().sort_values()

Denver Nuggets         0.332388
Boston Celtics         0.472204
Atalanta Hawks         0.477551
Cleveland Cavaliers    0.538914

Reorder and plotting:

sns.heatmap(df.reindex(df.mean().sort_values().index, axis=1),
cmap="coolwarm",annot=True)

Or:

sns.heatmap(df[df.mean().sort_values().index],cmap="coolwarm",annot=True)

enter image description here

Related