[R] highlighting clusters in a heatmap

David Winsemius dwinsemius at comcast.net
Fri Jul 1 03:26:38 CEST 2011

On Jun 30, 2011, at 8:02 PM, Levi Waldron wrote:

> I would like to draw horizontal or vertical lines on a heatmap to
> highlight the clusters at some specified cut depth of the dendrogram.
> As a hacked example, the following code would work if I could set the
> coordinates of the top and bottom of the false color image correctly
> (ymin and ymax), but the correct values seem to depend on the output
> device and its size.  I realize that heatmaps use a 2x2 layout which
> makes the coordinate system non-obvious, but the result seems very
> difficult to customize.  I would appreciate any suggestions for manual
> or pre-made solutions.

The code discloses the color image is made with the 'image' function  
and that its arguments include:

   ...,  xlim = 0.5 + c(0, nc), ylim = 0.5 + c(0, nr), ...

?image        # for details of coordinate choices.

Given the way the coordinate systems of that call  might get messed   
up by the subsequent 'plot' call, my guess is that the fastest way to  
get what you want is to hack 'heatmap' by adding a couple of argument  
and sticking a couple of "highlighting" functions just after the image  
call. (You haven't said how you are picking these levels.)


> Example:
> set.seed(2)
> x <- matrix(rnorm(1000),ncol=10)  #obviously no real clusters here...
> row.hclust <- hclust(dist(x))
> row.dendro <- as.dendrogram(row.hclust)
> heatmap(x,
>        Rowv=row.dendro)
> row.cut <- cutree(row.hclust,3)[row.hclust$order]
> cutpoints <- which(row.cut[-1]!=row.cut[-length(row.cut)])
> ymin <- par("usr")[3]    #in general incorrect
> ymax <- par("usr")[4]   #in general incorrect
> for (i in cutpoints){
>  thisy <- ymin + (ymax-ymin)*(i-1)/nrow(x)
>  abline(h=thisy,lw=3)
> }
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
West Hartford, CT

More information about the R-help mailing list