Mat*_*Aff 2 plot r flip ggplot2 ggdendro
我正在使用 ggdendrogram 来绘制树状图,但我希望将标签放在左侧以使图表更直观。我该怎么做呢?谢谢!!!
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)
Run Code Online (Sandbox Code Playgroud)
重点是代码ggdendrogram何时rotate=TRUE执行此操作:
if (rotate) {
p <- p + coord_flip()
p <- p + scale_y_reverse(expand = c(0.2, 0))
}
Run Code Online (Sandbox Code Playgroud)
但你不希望这样scale_y_reverse(.)做。所以,一种方法是你自己做coord_flip()。
ggdendrogram(hc, rotate=FALSE, theme_dendro=FALSE) + coord_flip()
Run Code Online (Sandbox Code Playgroud)
但是,一个明显的问题是这种labels做法不合理。而且您不能在ggdendrogram()函数内做太多事情,因为它不允许在外部进行设置hjust和angle属性。
因此,对于您的情况,我建议您ggplot()通过复制函数内的行来创建自己的代码ggdendrogram。
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()
Run Code Online (Sandbox Code Playgroud)
这给出:

另一种方法是您根据需要修改函数ggdendrogram并重新编译它。我认为这样做更容易,而且也正是您想要的: