You can try this solution, just change the "labs" to your "MS.groups" and "var", and your "MS.groups" will be converted to numeric (possibly with as.numeric). It comes from How to color the dendrogram labels of an additional factor variable in R
df <- structure(list(labs = c("a1", "a2", "a3", "a4", "a5", "a6", "a7",
"a8", "b1", "b2", "b3", "b4", "b5", "b6", "b7"), var = c(1L, 1L, 2L,
1L,2L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L), td = c(13.1, 14.5, 16.7,
12.9, 14.9, 15.6, 13.4, 15.3, 12.8, 14.5, 14.7, 13.1, 14.9, 15.6, 14.6),
fd = c(2L, 3L, 3L, 1L, 2L, 3L, 2L, 3L, 2L, 4L, 2L, 1L, 4L, 3L, 3L)),
.Names = c("labs", "var", "td", "fd"), class = "data.frame", row.names =
c(NA, -15L))
df.nw = df[,3:4]
labs = df$labs
d = dist(as.matrix(df.nw))
hc = hclust(d, method="complete")
plot(hc, hang=-0.01, cex=0.6, labels=labs, xlab="")
hcd = as.dendrogram(hc)
plot(hcd, cex=0.6)
Var = df$var
varCol = gsub("1","red",Var)
varCol = gsub("2","blue",varCol)
colLab <- function(n) {
if(is.leaf(n)) {
a <- attributes(n)
attr(n, "label") <- labs[a$label]
attr(n, "nodePar") <- c(a$nodePar, lab.col = varCol[a$label])
}
n
}
plot(dendrapply(hcd, colLab))