When add.expr is called, the graph is set so that the center of the cells is in unit integer values. Try adding add.expr = points (1: 5.1: 5). Now all you have to do is write a function that draws fields (help (rect)) with the colors you want in coordinates with full integers.
Try the following:
set.seed(310366) nx=5 ny=6 SOI=matrix(rnorm(nx*ny,100,50),nx,ny) colnames(SOI)=paste("NAP_G0",sort(as.integer(runif(ny,10,99))),sep="") rownames(SOI)=sample(2315101:(2315101+nx-1)) above150 = SOI>150 below30=SOI<30 makeRects <- function(tfMat,border){ cAbove = expand.grid(1:nx,1:ny)[tfMat,] xl=cAbove[,1]-0.49 yb=cAbove[,2]-0.49 xr=cAbove[,1]+0.49 yt=cAbove[,2]+0.49 rect(xl,yb,xr,yt,border=border,lwd=3) } heatmap(t(SOI),Rowv = NA, Colv=NA, add.expr = { makeRects(above150,"red");makeRects(below30,"blue")})
source share