Monday, April 15, 2013

RG#64: Dendogram and tree diagram with ggplot2 (ggdendro package)



 

# data
set.seed(1234)
P <- vector()
DF <- as.data.frame(matrix(rep(NA, 100), nrow=10))
names(DF) <- c(paste("M",1:10, sep=""))
for(i in 1:10) {
DF[,i] <- rnorm(10, 10, 3)
}
rownames (DF) <- paste("O", 1:10, sep = "")




library(ggplot2)
library(ggdendro)

hclt <- hclust(dist(DF))
p <- ggdendrogram(hclt, rotate=FALSE, size=2, theme_dendro = FALSE, color="tomato")
 print(p)

dhc <- as.dendrogram(hclt)
# Rectangular lines
 ddata <- dendro_data(dhc, type="rectangle")
 p <- ggplot(segment(ddata)) + geom_segment(aes(x=x, y=y, xend=xend, yend=yend), col = "purple", size = 2)+ coord_flip() + scale_y_reverse(expand=c(0.2, 0))+ theme_bw()
 print(p)
 
 
# drawn using triangular lines instead of rectangular lines.
ddata <- dendro_data(dhc, type="triangle")

 p <- ggplot(segment(ddata)) + geom_segment(aes(x=x, y=y, xend=xend, yend=yend), col = "green4", size = 1.5, lty = 1) +

 coord_flip() + scale_y_reverse(expand=c(0.2, 0)) +  theme_dendro()

 print(p)
 

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.