Data order in seaborn heatmap from pivot

mystifier picture mystifier · Apr 29, 2017 · Viewed 15.6k times · Source

So I have a heatmap created using seaborn

revels = rd.pivot("Flavour", "Packet number", "Contents")

ax = sns.heatmap(revels, annot=True, fmt="d", linewidths=0.4, cmap="YlOrRd")

plt.show()

which producesenter image description here

There are two things which I want to do however, which I can't for the life of me work out how to do, despite consulting seaborn's helpfile (http://seaborn.pydata.org/generated/seaborn.heatmap.html)

The thing I want to do is order the flavours differently. Despite the order being inputted in the textfile as orange, toffee, choc, malt, raisin, coffee, it doesn't generate this way when plotting. I tried to edit the yticklabs but that just edits the labels as opposed to moving the data with it.

Thanks for any help

PS data looks like this:

Packet number,Flavour,Contents
1,orange,4
2,orange,3
3,orange,2
...
1,toffee,4
2,toffee,3
3,toffee,3
...
etc.

Answer

Andrew L picture Andrew L · Apr 29, 2017

As for the first question, you'll need to perform the sort with your data. Your first line creates a dataframe which you can then use the sortlevel method to sort.

Create dataframe:

revels = rd.pivot("Flavour", "Packet number", "Contents")

Because you're using Flavour as the index, use the sortlevel method before adding to heatmap:

revels.sort_index(level=0, ascending=True, inplace=True)

This will change the order of your data in the heatmap.

This obviously provides ascending/descending sorting but if you need a custom sort order, try this link: Custom sorting in pandas dataframe.

Custom Sorting Example

revels.index = pd.CategoricalIndex(revels.index, categories= ["orange", "toffee", "chocolate", "malteser", "raisin", "coffee"])
revels.sort_index(level=0, inplace=True)