I am plotting a dendrogram of the moduleeigengenes in the WGCNA package and I want to order/swap the branches. I use the plotEigengeneNetworks
function to plot it, but cannot define the order of the branches. I know that there is the dendextend
package for modifying dendrograms, but this does not work on the output that plotEigengeneNetworks
function produces. I would be helpful for any suggestions on how to achieve this.
Example:
library(WGCNA)
set.seed(123)
ME <- data.frame(replicate(15, sample(1:10, 11, rep=TRUE)))
ME[,c(1:11)] <- sapply(ME[, c(1:11)], as.numeric)
plotEigengeneNetworks(ME, plotAdjacency = TRUE, setLabels = colnames(ME), plotDendrograms = TRUE, plotHeatmaps = FALSE)
Looking at the code of plotEigengeneNetworks, You will not be able to do what you want using it. However, what you can do is reproduce the way it creates the cluster, and then use the dendextend package to directly update the dendrogram (produced from the hclust), by using the following:
# we need to run all of this to get the relevant packages...
source("http://bioconductor.org/biocLite.R")
biocLite("S4Vectors")
biocLite("IRanges")
biocLite("GenomeInfoDb")
biocLite("AnnotationDbi")
biocLite("GO.db")
biocLite("WGCNA")
# what the author wanted:
library(WGCNA)
set.seed(123)
ME <- data.frame(replicate(15, sample(1:10, 11, rep=TRUE)))
ME[,c(1:11)] <- sapply(ME[, c(1:11)], as.numeric)
plotEigengeneNetworks(ME, plotAdjacency = TRUE, setLabels = colnames(ME), plotDendrograms = TRUE, plotHeatmaps = FALSE)
# =================================
# Reproduce the above plot:
corME = cor(ME)
disME = as.dist(1 - corME)
clust = fastcluster::hclust(disME, method = "average") # you could also use stats::hclust just as well...
plot(clust)
# Now that we got what we wanted, let's move to dendrogram land
dend <- as.dendrogram(clust)
# get dendextend
if(!require(dendextend)) install.packages("dendextend")
library(dendextend)
dend <- hang.dendrogram(dend)
# plot(dend) # it now looks similar to the hclust plot
# we can now rotate the labels:
dend <- color_labels(dend)
dend2 <- rotate(dend, order = sort(labels(dend)))
par(mfrow = c(1,2))
plot(dend, main = "Original dend plot")
plot(dend2, main = "Dend plot after rotating the labels")
#
Result: