使用locator()在热图上添加文本

时间:2013-10-03 19:26:51

标签: r text orientation heatmap labels

我正在通过heatmap.2()创建热图。我想把xaxis标签旋转45度。按照其他帖子中的说明,我尝试在没有x标签的情况下构建热图,然后使用text()添加它们... 这就是我试过的:

#fake matrix
cheese.matrix <- matrix(runif(100),10,10)
#build color palette
my.palette <- colorRampPalette(c("blue", "green", "yellow", "orange", "red"), space="rgb")
#build a first heatmap
hm_cheese <- heatmap.2(cheese.matrix,Rowv=NA,Colv=NA,col=my.palette,
                       density.info=c("none"),margins(3,5),cexRow=0.8,
                       cexCol=0.8,key=TRUE,keysize=1,trace="none",
                       lhei=c(2,8), breaks=100)
#find the coordinates on the plot where I want to pu the first and the last label
pos2 <- locator()
pos2
$x
[1] 0.08129779 0.90164993

$y
[1] -0.06905376 -0.06372554

pos2 <- structure(list(x=c(0.08129779, 0.90164993), y=c(-0.06905376, -0.06372554)), .Names=c("x","y"))
#create a vector with the labels I want to add
labs <- c("NWC1.PR", "CURD1.PR", "NWC2.PR","CURD2.PR","NWC3.PR","CURD3.PR",  "NWC4.PR", "CURD4.PR", "NWC5.PR", "CURD5.PR")
#build another heatmap
hm_cheese <- heatmap.2(cheese.matrix,Rowv=NA,Colv=NA,col=my.palette,
                      density.info=c("none"),margins(3,5),key=TRUE,
                      keysize=1,trace="none", lhei=c(2,8), breaks=100, 
                      labCol="", add.expr=text(x=seq(pos2$x[1], pos2$x[2], len=10),
                      y=rep(pos2$y[1],10), srt=45, xpd=TRUE, adj=0, labels=labs))

这将标签贴在热图上,但所有名称都覆盖了...... 我也试过这个:

hm_cheese2 <-heatmap.2(cheese.matrix,Rowv=NA,Colv=NA,col=my.palette,
                       density.info=c("none"),margins(3,5),key=TRUE,keysize=1,
                       trace="none", lhei=c(2,8), breaks=100, labCol="", 
                       add.expr=text(x=seq_along(labs), y=-0.06372554, srt=45,
                       xpd=TRUE, adj=0, labels=labs))

结果更好,因为标签沿着轴线,但仍然非常接近它们并覆盖在情节上......

我使用locator()查找坐标的方式有什么问题吗? 任何人都可以帮我改进我的代码吗?

1 个答案:

答案 0 :(得分:3)

您可以在致电pos时使用参数text。以pos=1为例:

hm_cheese2 <-heatmap.2(cheese.matrix,Rowv=NA,Colv=NA,col=my.palette,
                       density.info=c("none"),margins(3,5),key=TRUE,keysize=1,
                       trace="none", lhei=c(2,8), breaks=100, labCol="", 
                       add.expr=text(x=seq_along(labs), y=-0.06372554, srt=45,
                       xpd=TRUE, adj=0, labels=labs, pos=1))

enter image description here

有关?text的更多信息,请参阅pos

如果标签不在图中,您可以尝试使用xpd=NA将它们剪切到设备区域而不是图形或图形区域。

hm_cheese2 <-heatmap.2(cheese.matrix,Rowv=NA,Colv=NA,col=my.palette,
                       density.info=c("none"),margins(3,5),key=TRUE,keysize=1,
                       trace="none", lhei=c(2,8), breaks=100, labCol="", 
                       add.expr=text(x=seq_along(labs), y=-0.06372554, srt=45,
                       xpd=NA, adj=0, labels=labs, pos=1))