0

I am trying to control the order and colour of a dendrogram. Obviously the point of the dendorgram is to order by similarity, but within branches I'd like to set an order that make sense (alphabetical-numeric).

library(vegan)
library(stats) 

x <-data.frame(data = c(1:10)) 
y = data.frame(type = c("A","B","C","A","C","D","A","B","C","B"), site_name = c("A1","B1","C1","A2","C2","D1","A3","B2","C3","B3"))  
row.names(x) = y$site_name 
dis = vegdist(x) 
hc <- hclust(dis) 
dd <- as.dendrogram(hc) 
plot(dd)

enter image description here

My data labels are text but they do have a set order listed in a variable

site_order = c("A1","A2","A3","B1","B2","B3","C1","C2","C3","D1")

1) I'd like to find a solution that sorts the dendogram according to site_order within branches.

e.g. A1,B1, A2, C1, C2,D2, A3,B2, B3,C3

I also want to colour and shape the labels using site_type e.g (A= red circle , B= blue square , C= green triangle, D = yellow cross)

Is this possible?

Tal Galili
  • 24,605
  • 44
  • 129
  • 187
Birdonawire
  • 199
  • 3
  • 10

1 Answers1

0

This is a job best done using the rotate function from dendextend.

library(vegan)
library(stats) 

x <-data.frame(data = c(1:10)) 
y = data.frame(type = c("A","B","C","A","C","D","A","B","C","B"), site_name = c("A1","B1","C1","A2","C2","D1","A3","B2","C3","B3"))  
row.names(x) = y$site_name 
dis = vegdist(x) 
hc <- hclust(dis) 
dd <- as.dendrogram(hc) 

par(mfrow = c(1,2))
plot(dd, main = "orig")

library(dendextend)
dd2 <- rotate(dd, sort(labels(dd)) )
plot(dd2, main = "as sorted as possible \n(under the constraints)")

Output:

enter image description here

You can learn more on the dendextend package from the online vignettes.

Tal Galili
  • 24,605
  • 44
  • 129
  • 187