Question

I'm doing cluster analysis and creating a dendrogram. I used ggdendrogram package and want to use its output in ggplot2. I wonder how get the same x-labels as the leaf-labels. Thanks

D1 <- as.dist(
  matrix(
    data=
    c(   0,  9, 3, 6, 11
      ,  9,  0, 7, 5, 10
      ,  3,  7, 0, 9,  2
      ,  6,  5, 9, 0,  8
      , 11, 10, 2, 8,  0)
    , nrow= 5
    , ncol = 5
    , byrow=TRUE
    ))

HCD1 <- hclust(d = D1, method="single", members=NULL)
library(ggdendro)
ggdendrogram(HCD1, theme_dendro=FALSE)

enter image description here

HCD1Data <- dendro_data(as.dendrogram(HCD1))

library(ggplot2)
p1 <-
    ggplot(data = HCD1Data$segments) +
    geom_segment(aes(x=x, y=y, xend=xend, yend=yend))
print(p1)

enter image description here

Was it helpful?

Solution

You can use scale_x_discrete() and set your own labels. The same labels as in dendrogram are located in object HCD1Data parts labels and column label.

HCD1Data$labels
  x y label
1 1 0     1
2 2 0     3
3 3 0     5
4 4 0     2
5 5 0     4

p1+scale_x_discrete(labels=HCD1Data$labels$label)

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top