在ggplot热图中给出4个点的绘图矩形

时间:2014-12-26 17:39:24

标签: r

我在txt文件(fruits2612e.txt)

中有这些数据
"people","1","2","3","4","5","6","7","8","9","10","11","12"
"Ej1",0,0,0,0,0,0,0,0,0,0,0,0
"Ej2",0,0,1,1,1,1,1,1,0,0,0,0
"Ej3",0,0,0,0,0,0,1,0,0,0,0,0
"Ej4",0,1,1,1,0,0,1,1,0,0,0,1
"Ej5",1,1,1,1,1,1,1,1,0,0,0,1
"Ej6",1,1,1,1,0,1,1,1,0,0,1,1
"Ej7",1,1,1,1,1,1,1,1,0,0,0,0
"Ej8",0,0,0,1,1,1,0,0,0,0,0,0
"Ej9",0,0,1,1,1,1,1,1,0,0,0,0
"Ej10",0,0,0,1,1,1,1,0,0,0,0,0
"Ej11",0,0,0,0,1,0,0,0,0,1,1,0
"Ej12",0,0,1,1,1,0,0,0,0,1,1,1
"Ej13",0,1,1,1,0,0,0,1,1,1,1,1
"Ej14",1,1,0,0,0,0,0,1,1,1,0,1
"Ej15",0,0,0,0,0,0,0,1,1,1,1,1
"Ej16",0,0,0,0,0,0,0,1,1,1,1,1

我使用此代码构建了热图(没有黑色矩形)

library(reshape2)
library(ggplot2)
library(scales)
library(plyr)
data <- read.csv("fruits2612e.txt", head=TRUE, sep=",")
data$people <- factor(data$people,levels=rev(data$people))
data.m = melt(data)
#data.m <- ddply(data.m, .(variable), transform, rescale = rescale(value))
data.m[,"rescale"]<-rescale(data.m[,"value"],to=c(0,1))
fewer.labels <- c("Ej16","Ej15","Ej14","Ej13","Ej12","Ej11","Ej10","Ej9","Ej8","Ej7","Ej6","Ej5","Ej4","Ej3","Ej2","Ej1")
p <- ggplot(data.m, aes(variable, people)) +
     geom_tile(aes(fill = rescale), colour = "white") +
     scale_y_discrete(labels=fewer.labels) +
     scale_fill_gradient(low = "red", high = "green") +
     theme(axis.text=element_text(size=8))

现在我正在尝试将黑色矩形添加到热图中,但无法找到如何,坐标

maxR<-c(topLeftx,topLefty,botRightX,botRightY)
[1] 5 1 7 8

enter image description here

2 个答案:

答案 0 :(得分:4)

按照我自己的建议,我搜索了#34;注释geom rect&#34;并找到一个命中:Draw multiple squares with ggplot

maxR<-c(topLeftx=5,topLefty=1,botRightX=7,botRightY=8)
 p +  annotate(geom='rect', xmin= maxR['botRightX'], ymin= maxR['botRightY'],
                            xmax=maxR['topLeftx'], ymax=  maxR['topLefty'], 
                fill="transparent", col="black", lwd=3)

所以显然我们对如何指定矩形的索引有不同的概念,但你应该可以从这里开始。

enter image description here

答案 1 :(得分:2)

ggplot使用他们的代码在内部操纵因素,这些代码可以使用例如as.integer(data.m$people)等等。瓷砖的角是代码+/- 0.5。所以,假设你确实在x方向和y方向都使用因子,那么这将绘制你想要的方框

maxR     <-c(topLeftx=5,topLefty=1,botRightX=7,botRightY=8)
sub.data <- with(data.m,
                 with(as.list(maxR),
                      data.m[people %in% paste0("Ej",topLeftx:botRightX) 
                             & variable %in% paste0("X",topLefty:botRightY),]))

p+with(sub.data,annotate(geom="rect", fill="transparent",color="black", size=1.5,
           xmin=min(as.integer(variable))-0.5,ymin=min(as.integer(people))-0.5,
           xmax=max(as.integer(variable))+0.5,ymax=max(as.integer(people))+0.5))

由于您选择指定方框角落的奇怪方式,因此需要在开始时使用折磨代码。