2

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

MYaseen208
  • 22,666
  • 37
  • 165
  • 309
  • why do you show two examples - what is the key difference, and what else do you want to add? (from the question it sounds like the first figure provides what you are looking for, but pardon me if I misunderstood) – David LeBauer May 08 '13 at 04:41
  • @David -- I believe the OP wants a figure like the second one, but with the x-axis tick labels reading, from left to right, "1", "3", "5", "2", "4" (instead of "1", "2", "3", "4", "5"). – Josh O'Brien May 08 '13 at 04:51
  • Thanks @David and Josh for showing your interest in my problem. Josh is right that I want the x-axis tick labels reading, from left to right, "1", "3", "5", "2", "4" (instead of "1", "2", "3", "4", "5") – MYaseen208 May 08 '13 at 04:53

1 Answers1

7

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

Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201