문제

I'm using a ggdendrogram to plot a dendrogram, but I want to have the labels on the left to make the graph more intuitive. How do I do this? Thanks!!!

library(ggplot2)
library(ggdendro)

### Data
countries <- c("UK","AU","SA","CH")
distmatrix <- matrix(c(0.00, 0.16, 1.01, 0.97, 0.16, 0.00, 0.84, 0.79, 1.01, 0.84, 0.00, 1.49, 0.97, 0.79, 1.49, 0.00),
nrow=4,dimnames=list(countries, countries))

### Cluster
hc = hclust(as.dist(distmatrix), method = "ward")

### Plot
ggdendrogram(hc, rotate=TRUE, theme_dendro=FALSE)
도움이 되었습니까?

해결책

The point is that the code ggdendrogram when rotate=TRUE does this:

if (rotate) {
    p <- p + coord_flip()
    p <- p + scale_y_reverse(expand = c(0.2, 0))
}

But you don't want that scale_y_reverse(.) to be done. So, one way is for you to do the coord_flip() yourself.

ggdendrogram(hc, rotate=FALSE, theme_dendro=FALSE) + coord_flip()

But, one obvious problem is that the labels would't justified properly. And you can't do much within ggdendrogram() function because it doesn't allow setting hjust and angle properties externally.

So, I'd suggest for your case, that you create the ggplot() yourself by copying the lines from within ggdendrogram function.

data <- dendro_data(hc)
p <- ggplot() + geom_segment(data = segment(data), 
              aes_string(x = "x", y = "y", xend = "xend", yend = "yend"))
p <- p + geom_text(data = label(data), 
              aes_string(x = "x", y = "y", label = "label"), hjust = 1, angle = 0)
p + scale_y_continuous(expand=c(0.2, 0)) + coord_flip()

This gives:

enter image description here

Another way is for you to modify the ggdendrogram function to your needs and re-compile it. I think it's much easier to do it this way and is quite what you want as well:

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top