Didzis Elferts showed how to plot a dendogram using ggplot2 and ggdendro:
horizontal dendrogram in R with labels
here is the code:
labs = paste("sta_",1:50,sep="") #new labels
rownames(USArrests)<-labs #set new row names
hc <- hclust(dist(USArrests), "ave")
library(ggplot2)
library(ggdendro)
#convert cluster object to use with ggplot
dendr <- dendro_data(hc, type="rectangle")
#your own labels are supplied in geom_text() and label=label
ggplot() +
geom_segment(data=segment(dendr), aes(x=x, y=y, xend=xend, yend=yend)) +
geom_text(data=label(dendr), aes(x=x, y=y, label=label, hjust=0), size=3) +
coord_flip() + scale_y_reverse(expand=c(0.2, 0)) +
theme(axis.line.y=element_blank(),
axis.ticks.y=element_blank(),
axis.text.y=element_blank(),
axis.title.y=element_blank(),
panel.background=element_rect(fill="white"),
panel.grid=element_blank())
Does anyone know, how to colorize the different clusters? For example, you want to have 2 Clusters (k=2) colorized?
Workaround would be to plot cluster object with
plot()
and then use functionrect.hclust()
to draw borders around the clusters (nunber of clusters is set with argumentk=
). If result ofrect.hclust()
is saved as object it will make list of observation where each list element contains observations belonging to each cluster.Now this list can be converted to dataframe where column
clust
contains names for clusters (in this example two groups) - names are repeated according to lengths of list elemets.New data frame is merged with
label()
information ofdendr
object (dendro_data()
result).When plotting dendrogram use
text.df
to add labels withgeom_text()
and use columnclust
for colors.Adding to @DidzisElferts' and @jlhoward's code, the dendrogram itself can be coloured.
The 2-cluster and 4-cluster solutions:
This approach is very similar to @DidzisElferts', just a little simpler.
A short way to achieve a similar result is to use the package
dendextend
(derived from this nice overview).Note: The order of the states is slightly different compared to those above - not really changing interpretation though.