Seaborn热图中来自数据透视的数据顺序 [英] Data order in seaborn heatmap from pivot

查看:227
本文介绍了Seaborn热图中来自数据透视的数据顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个使用seaborn创建的热图

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()

产生

尽管有咨询seaborn的帮助文件(

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)

我想做的就是以不同的顺序订购口味.尽管在文本文件中输入的顺序为橙色,太妃糖,巧克力,麦芽,葡萄干,咖啡,但在绘制时不会以这种方式生成.我试图编辑yticklabs,但这只是编辑标签,而不是随其移动数据.

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.

感谢您的帮助

PS数据如下:

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

推荐答案

对于第一个问题,您需要对数据进行排序.您的第一行将创建一个数据框,然后您可以使用sortlevel方法对其进行排序.

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.

创建数据框:

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

因为您使用Flavor作为索引,所以在添加到热图之前使用sortlevel方法:

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.

自定义排序示例

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

这篇关于Seaborn热图中来自数据透视的数据顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆