pandas 来自枢轴的seaborn热图中的数据顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43694368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Data order in seaborn heatmap from pivot
提问by mystifier
So I have a heatmap created using seaborn
所以我有一个使用 seaborn 创建的热图
revels = rd.pivot("Flavour", "Packet number", "Contents")
ax = sns.heatmap(revels, annot=True, fmt="d", linewidths=0.4, cmap="YlOrRd")
plt.show()
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)
然而,我想做两件事,尽管查阅了 seaborn 的帮助文件 ( 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.
我想要做的就是以不同的方式订购口味。尽管在文本文件中输入的顺序为橙子、太妃糖、巧克力、麦芽、葡萄干、咖啡,但在绘图时不会以这种方式生成。我试图编辑 yticklabs 但这只是编辑标签而不是移动数据。
Thanks for any help
谢谢你的帮助
PS data looks like this:
PS数据如下所示:
Packet number,Flavour,Contents
1,orange,4
2,orange,3
3,orange,2
...
1,toffee,4
2,toffee,3
3,toffee,3
...
etc.
采纳答案by Andrew L
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.
至于第一个问题,您需要对数据进行排序。您的第一行创建了一个数据框,然后您可以使用 sortlevel 方法进行排序。
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:
因为您使用 Flavor 作为索引,所以在添加到热图之前使用 sortlevel 方法:
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.
这显然提供了升序/降序排序,但如果您需要自定义排序顺序,请尝试此链接: 在Pandas数据框中自定义排序。
Custom Sorting Example
自定义排序示例
revels.index = pd.CategoricalIndex(revels.index, categories= ["orange", "toffee", "chocolate", "malteser", "raisin", "coffee"])
revels.sort_index(level=0, inplace=True)
回答by bracoo
The above example works, but you have to replace sortlevel
with sort_index
上面的例子有效,但你必须替换sortlevel
为sort_index
i.e. revels.sortlevel(level=0, ascending=True, inplace=True)
becomes revels.sort_index(axis=0, ascending=True, inplace=True)
即revels.sortlevel(level=0, ascending=True, inplace=True)
变成revels.sort_index(axis=0, ascending=True, inplace=True)