2014-12-26 18 views
1

我有這樣的數據在一個txt文件使用此代碼情節矩形給出ggplot熱圖4分

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

我建立了熱圖(不帶黑色矩形)

現在我想的黑色矩形添加到熱圖,但不能找出如何座標,是

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

enter image description here

+0

你應該看看'annotate'函數,並研究'geom ='rect''是否提供了一個解決方案。 –

+0

這可能有助於:http://stackoverflow.com/questions/22024641/how-to-add-bounding-box-to-a-specific-area-in-ggplot2-heatmap – KFB

+0

非常感謝! – user3437823

回答

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

需要在開始的折磨,因爲代碼的盒子這是你選擇指定盒子角落的奇怪方式。

+0

非常感謝! – user3437823

4

按照我自己的意見,我搜索的SO爲「註解GEOM矩形」,發現一重擊: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