在绘制热图时,标签顺序怎么都不按自己的想法,整的我都快没脾气了。类似这种:
rm(list = ls())
library(pheatmap)
test <- matrix(rnorm(100),20,20)
test[1:10,seq(1,10,2)]=test[1:10,seq(1,10,2)]+4
test[11:20, seq(2, 10, 2)] = test[11:20, seq(2, 10, 2)] + 6
test[15:20, seq(2, 10, 2)] = test[15:20, seq(2, 10, 2)] + 8
colnames(test) = paste("Test", 1:20, sep = "")
rownames(test) = c(paste("Gene", seq(2,20,by=2),"**", sep = ""),paste("Gene", seq(1,19,by=2),"", sep = ""))
pheatmap(test)
Type=c(rep("N",10),rep("T",10))
names(Type)=colnames(test)
Type <- as.data.frame(Type)
pheatmap(test,
cluster_rows = F,
cluster_cols = F,
scale = "row",
annotation_col = Type)
首先自定义需要的顺序:
genelist <- c('Gene1','Gene2**','Gene3','Gene4**','Gene5','Gene6**','Gene7','Gene8**','Gene9','Gene10**','Gene11','Gene12**','Gene13','Gene14**','Gene15','Gene16**','Gene17','Gene18**','Gene19','Gene20**')
genelist <- factor(genelist,levels = genelist)
genelist
[1] Gene1 Gene2** Gene3 Gene4** Gene5 Gene6** Gene7 Gene8** Gene9 Gene10**
[11] Gene11 Gene12** Gene13 Gene14** Gene15 Gene16** Gene17 Gene18** Gene19 Gene20**
20 Levels: Gene1 Gene2** Gene3 Gene4** Gene5 Gene6** Gene7 Gene8** Gene9 Gene10** ... Gene20**
这时按照这个顺序去排序rownames是不是就可以了呢?试一试
test <- test[genelist,]
head(test)
Test1 Test2 Test3 Test4 Test5 Test6 Test7 Test8 Test9
Gene2** 4.176043 -1.2732772 3.148016 0.7637291 5.743130 0.1760431 2.726723 -0.8519841 4.763729
Gene4** 5.273485 0.1687609 4.919915 0.1974605 5.653718 1.2734848 4.168761 0.9199151 4.197461
Gene6** 3.382290 -0.1863888 5.285244 -0.4088611 4.174547 -0.6177103 3.813611 1.2852440 3.591139
Gene8** 3.277272 -1.1306419 2.638180 1.2198956 5.597580 -0.7227279 2.869358 -1.3618202 5.219896
Gene10** 3.231016 0.4078852 4.543947 -1.4453278 4.500175 -0.7689839 4.407885 0.5439469 2.554672
Gene12** 4.708585 -0.6848347 5.374241 -2.0126771 3.536655 0.7085849 3.315165 1.3742411 1.987323
好像根本没有用,这可咋办呢?
思考:我们只是需要将行名按照自己需求的顺序排列,顺序其实就是位置信息嘛,位置信息最好的转化方法是match呀。
match粉墨登场
test <- test[match(genelist,rownames(test)),]
test <- t(scale(t(test)))
pheatmap(test,
cluster_rows = F,
cluster_cols = F,
scale = "row",
annotation_col = Type)
竟然神奇的按照需要的顺序排列了
总结
核心函数:
test[match(genelist, rownames(test)),]