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))
有帮助吗?

解决方案

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)

其他提示

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") 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top