How to add clustering rectangle in hierarchical heatmap dendogram

cluster-analysis, plot, r

Solution

May I suggest an alternative, by using `RowSideColors` argument in the `heatmap.2` function:

heatmap.2(as.matrix(mydata),dendrogram="row",trace="none", margin=c(8,9), 
         hclust=hclustfunc, distfun=distfunc, RowSideColors=as.character(groups))

If you wish to reassign the colours:

# require(RColorBrewer)
cols <- brewer.pal(max(groups), "Set1")
heatmap.2(as.matrix(mydata),dendrogram="row",trace="none", margin=c(8,9), 
         hclust=hclustfunc, distfun=distfunc, RowSideColors=cols[groups])

The first example is shown below:

Problem

The following code create 1. Dendogram and 2. Heatmap with dendogram ``` mydata <- mtcars hclustfunc <- function(x) hclust(x, method="complete") distfunc <- function(x) dist(x,method="euclidean") d <- distfunc(mydata) fit <- hclustfunc(d) #plot dendogram only plot(fit) groups <- cutree(fit, k=5) # Add rectangle in cluster rect.hclust(fit, k=5, border="red") ``` Which generate this plot: Now I want to create a heat map with dendogram ``` # plot heat map with dendogram together. library("gplots") heatmap.2(as.matrix(mydata),dendrogram="row",trace="none", margin=c(8,9), hclust=hclustfunc,distfun=distfunc); ``` Currently it looks like this: In the final heat map is there a way I can add the red rectangle for each cluster (i.e. onto the dendogram on the left) just like first figure?

Original source