简体   繁体   中英

How to manually create a dendrogram matrix for heatmap.2 in R?

Here is an example of my heatmap created by gplots::heatmap.2 :

df<-data.frame(x1=rnorm(100),x2=rnorm(100,2,3),x3=rnorm(100,10,1),
           y1=rnorm(100,5,1),y2=rnorm(100,20,5),y3=rnorm(100,30,2))
cor<-cor(df)

require(gplots)
heatmap.2(cor,trace="none",col=bluered)#fig1
heatmap.2(cor,Rowv=F,Colv=F,dendrogram="none",trace="none",col=bluered)#fig2

I would like create a dendrogram in fig2 where Xs are manually grouped together as well as Ys so that I can compare the correlation figures with fig1 where the dendrogram is computed using distance. Does anybody know how to make that?

You can create a dendrogram object by hand, but to me the question leaves it a bit unclear as to why this information is needed in the figure 2. If a dendrogram, that clusters all x's and y's together as separate groups, is added to the figure 2, the branches of the dendrogram will cross each other, and render the dendrogram (using real branch lenghts or heights) unreadable. If a dendrogram using some suitable heights is added, the dendrogram branch lengths do not have meaning (they do not correspond to the real correlation coefficients), but the dendrogram still tells the branching order of the tree.

Anyway, here's how to go about this technically (also, see Aniko's answer to a similar question, the details are available there).

An hclust object (a), that uses the "real" (I calculated them fast, so they might not be exactly correct, please use hierarchical clustering algorithm with average linkage to check, if needed) branch lenghts can be generated by hand:

a<-list()
a$merge<-matrix(c(-1, -2,
                  -4, -5,
                  -3, 1,
                  -6, 2,
                  3, 4), ncol=2, byrow=TRUE)
a$height<-c(0.1, 0.12, 0.12, 0.045, 0.1)
a$order<-1:6
a$labels<-c("x1", "x2", "x3", "y1", "y2", "y3")
class(a)<-"hclust"

Or by using just some suitable branch lenghts to even get a dendrogram:

b<-list()
b$merge<-matrix(c(-1, -2,
                  -4, -5,
                  -3, 1,
                  -6, 2,
                  3, 4), ncol=2, byrow=TRUE)
b$height<-c(0.1, 0.1, 0.1, 0.1, 0.2)
b$order<-1:6
b$labels<-c("x1", "x2", "x3", "y1", "y2", "y3")
class(b)<-"hclust"

After that, the final plot can be generated as:

heatmap.2(cor,Rowv=as.dendrogram(a),Colv=as.dendrogram(a),trace="none",col=bluered)#fig2

or:

heatmap.2(cor,Rowv=as.dendrogram(b),Colv=as.dendrogram(b),trace="none",col=bluered)#fig2

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