Data order in seaborn heatmap from pivot

雨燕双飞 提交于 2019-12-10 15:25:39

问题


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 produces

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.

回答1:


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.sortlevel(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.sortlevel(level=0, inplace=True)



回答2:


The above example works, but you have to replace sortlevel with sort_index

i.e. revels.sortlevel(level=0, ascending=True, inplace=True) becomes revels.sort_index(axis=0, ascending=True, inplace=True)



来源:https://stackoverflow.com/questions/43694368/data-order-in-seaborn-heatmap-from-pivot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!