简体   繁体   中英

access coordinates heatmap.2 in R

I have drawn a plot with heatmap.2 for two variables each defined on [0,1]. I now want to draw, say, an abline(v=0.2) . This will be "misplaced" (relative to what I want, not the internal logid of R, I presume) as heatmap.2 also places other things in the plot area, like the color key (and the axes of heatmap are, I guess, internally other things, too, as I just rename the axes in the example below).

My question: how can I place things like an abline most conveniently, ideally in terms of the coordinates of the actual heatmap, not the entire plot area.

rm(list=ls())
library(rpart)
library(gplots)
library(RColorBrewer)

N <- 150

# just some data
X1 <- runif(N)
X2 <- runif(N)
y <- as.factor((X1<.2+rnorm(N,sd=0.2))|(X2>.7+rnorm(N,sd=0.1)))   

theData <- data.frame(y,X1,X2)

X1grid <- seq(0,1,by=.02)
X2grid <- seq(0,1,by=.02)
newData <- expand.grid(X2=X2grid,X1=X1grid)

FitSingle <- rpart(y~.,data=theData)
PredictionsSingle <- matrix(as.logical(predict(FitSingle, newdata=newData, type="class"))+0,nrow=length(X2grid))

names <- rep("", length(X2grid)) 
names[seq(1,length(X2grid), length(X2grid)/10)] <- seq(0, .9, by=.1) # not fully checked, but should be OK
rownames(PredictionsSingle) <- names
colnames(PredictionsSingle) <- names

rc <- colorRampPalette(c("darkgreen", "white", "purple3"))(n = nrow(X2grid))
heatmapplotSingle <- heatmap.2(PredictionsSingle, Rowv=NA, Colv=NA, col=rc,density.info="none",trace="none",revC=T)
abline(v=0.2) # should be at 0.2, not at roughly .6. should also stay in the heatmap

as mentioned in the comment, add.expr is the way to go:

heatmapplotSingle <- heatmap.2(PredictionsSingle, Rowv = NA, Colv = NA, col = rc, 
                           density.info = "none", trace = "none", revC = T,
                           main = "Classification Tree full sample", 
                           add.expr  = { segments(0.2*ncol(MeanPrediction), 0, 0.2*ncol(MeanPrediction),
                                                  .7*nrow(MeanPrediction), lwd = 3, col="darkslateblue");
                                         segments(0.2*ncol(MeanPrediction), .7*nrow(MeanPrediction), 1*ncol(MeanPrediction), 
                                                  .7*nrow(MeanPrediction), lwd = 3, col = "darkslateblue")}
                           , srtCol = 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM