从热图按行/列索引突出显示子集单元格

时间:2017-08-26 00:23:09

标签: r heatmap

我试图目视检查并提取大型热图的子集。例如,我想粗略地提取集群的行/列索引,就像我在下面圈出的那样:

desired heatmap subset

根据here的建议,我希望通过索引创建围绕单元子集的矩形并重复,直到我突出显示足够接近我想要的区域。

使用一些更简单的数据,我尝试了这个:

    library(gplots)

    set.seed(100)

    # Input data 4x5 matrix
    nx <- 5
    ny <- 4
    dat <- matrix(runif(20, 1, 10), nrow=ny, ncol=nx)

    # Get hierarchically clustered heatmap matrix
    hm <- heatmap.2(dat, main="Test HM", key=T, trace="none")
    hmat <- dat[rev(hm$rowInd), hm$colInd]

    # Logical matrix with the same dimensions as our data
    # indicating which cells I want to subset
    selection <- matrix(rep(F,20), nrow=4)
    # For example: the third row
    selection[3,] <- T

    #selection <- dat>7 # Typical subsets like this don't work either

    # Function for making selection rectangles around selection cells
    makeRects <- function(cells){
      coords = expand.grid(1:nx,1:ny)[cells,]
      xl=coords[,1]-0.49
      yb=coords[,2]-0.49
      xr=coords[,1]+0.49
      yt=coords[,2]+0.49
      rect(xl,yb,xr,yt,border="black",lwd=3)
    }

    # Re-make heatmap with rectangles based on the selection
    # Use the already computed heatmap matrix and don't recluster
    heatmap.2(hmat, main="Heatmap - Select 3rd Row", key=T, trace="none", 
      dendrogram="none", Rowv=F, Colv=F,
      add.expr={makeRects(selection)})

这不起作用。这是结果。我们看到一个奇怪的模式,而不是突出显示第三行:

strange subset returned

必须与此行有关:

    coords = expand.grid(1:nx,1:ny)[cells,]
    # with parameters filled...
    coords = expand.grid(1:5,1:4)[selection,]

有人能解释一下这里发生了什么吗?我不确定为什么我的子集不起作用,即使它与另一个问题中的那个相似。

1 个答案:

答案 0 :(得分:3)

非常接近。我认为你在makeRects()函数中输入了一个拼写错误。在我手中,它有一些变化。

# Function for making selection rectangles around selection cells
makeRects <- function(cells){
  coords = expand.grid(ny:1, 1:nx)[cells,]
  xl=coords[,2]-0.49
  yb=coords[,1]-0.49
  xr=coords[,2]+0.49
  yt=coords[,1]+0.49
  rect(xl,yb,xr,yt,border="black",lwd=3)
}

# Re-make heatmap with rectangles based on the selection
# Use the already computed heatmap matrix and don't recluster
heatmap.2(hmat, main="Heatmap - Select 3rd Row", key=T, trace="none",
          dendrogram="none", Rowv=F, Colv=F,
          add.expr={makeRects(selection)})

enter image description here