1

How can I add labels to a ggdendro plot? I realise from reading ?dendro_data that I am suppose to use the the call 'labels' but can't find an example of actual implementation. Could anybody please demonstrate how to add leaf labels to the example below. Thank you

require(ggplot2)

hc <- hclust(dist(USArrests), "ave")
dhc <- as.dendrogram(hc,hang=0.1)
ddata <- dendro_data(dhc, type="rectangle")
ggplot(segment(ddata)) + geom_segment(aes(x=x, y=y, xend=xend, yend=yend))
smillig
  • 5,073
  • 6
  • 36
  • 46
Elizabeth
  • 6,391
  • 17
  • 62
  • 90

2 Answers2

1

You can add leaf labels with a call to geom_text() using the data frame generated by label(ddata). I also extended the plot range using scale_y_continuous so the labels were not cutoff .

p <- ggplot(segment(ddata)) + geom_segment(aes(x=x, y=y, xend=xend, yend=yend))
p + geom_text(aes(x = x, y = y, label = label, angle = -90, hjust = 0), data= label(ddata)) +
  scale_y_continuous(expand = c(0.3, 0))

It may, however, be preferable to use ggdendrogram() unless you do not like the way those labels are displayed:

ggdendrogram(ddata)
orizon
  • 3,159
  • 3
  • 25
  • 30
  • Thanks so much. Just one more tiny question....is there any way to adjust the labels so that when hang=0.1 they will be positioned near to wear the branch ends and no all along the bottom? Thanks. – Elizabeth Sep 28 '12 at 08:10
  • The answer is yes, but it would require substantial work. Variable hang does not seem to implemented at all in the ``ggdendro`` package so we could not use ``dendro_data`` without heavy modification. – orizon Sep 28 '12 at 09:01
  • @orizon I agree. The only thing I manage is to push them a bit away from the endings of the branches with `nudge_x` or `nudge_y` in `geom_text`. – 5th Jul 19 '17 at 14:44
0

I was able to plot hanging dendrograms in ggdendro without a substantial amount of work by applying the following. You just have to construct a dataframe of the labels that also contains the leaf positions. This is done by filtering out the points to only take integers.

# tree is a an extracted dendro_data() object.
label_data <- bind_cols(filter(segment(tree), x == xend & x%%1 == 0), label(tree))

ggplot() + 
geom_segment(data=segment(tree), aes(x=x, y=y, xend=xend, yend=yend)) +
geom_text(data=label_data, aes(x=xend, y=yend, label=label, hjust=0, color = LT), size=2) +
coord_flip() + 
scale_y_reverse(expand=c(0.2, 0)) +
theme_bw() +
theme(panel.border = element_blank(),
      panel.grid.major = element_blank(), 
      panel.grid.minor = element_blank(),
      axis.line = element_blank(),
      axis.title = element_blank(),
      axis.text = element_blank(),
      axis.ticks = element_blank(),
      legend.position = "None")