R和rect.hclust:树形图中标签上的矩形

时间:2016-07-06 16:29:29

标签: r labels dendrogram dendextend

我是第一次构建树状图,并且在标签顶部绘制了簇周围的矩形。你知道如何修改这些标签的位置以避免这种重叠吗?

在这里你可以找到我的代码的一个工作示例:

mydata <- c(9.45, 10.54, 10.36, 10.46, 10.78, 10.1, 11.13)
mydata.matrix <- matrix(mydata, nrow = 1, ncol = 7)
colnames(mydata.matrix) <- c("a", "b", "c", "d", "e", "f", "g")
rownames(mydata.matrix) <- c("X")

d <- dist(mydata.matrix["X", ], method = "euclidean")
fit <- hclust(d, method="ward.D")

nodePar <- list(lab.cex = 0.6, pch = c(NA, 19), cex = 0.7, col = "blue")
plot(as.dendrogram(fit), xlab = "", sub="", ylab = "Euclidean distance",
     main = "Dendrogram", nodePar = nodePar)

rect.hclust(fit, k=2, border="red")

以下是上述代码中的情节:

Worked example of dendrogram

特别是我希望红色矩形完全包含树状图叶子的标签。

谢谢!

1 个答案:

答案 0 :(得分:2)

您应该使用dendextend package.

中的rect.dendrogram功能

例如:

mydata <- c(9.45, 10.54, 10.36, 10.46, 10.78, 10.1, 11.13)
mydata.matrix <- matrix(mydata, nrow = 1, ncol = 7)
colnames(mydata.matrix) <- c("a", "b", "c", "d", "e", "f", "g")
rownames(mydata.matrix) <- c("X")

d <- dist(mydata.matrix["X", ], method = "euclidean")
fit <- hclust(d, method="ward.D")

nodePar <- list(lab.cex = 0.6, pch = c(NA, 19), cex = 0.7, col = "blue")
dend <- as.dendrogram(fit)
plot(dend, xlab = "", sub="", ylab = "Euclidean distance",
     main = "Dendrogram", nodePar = nodePar)

library(dendextend)
rect.dendrogram(dend , k=2, border="red")

你会得到: enter image description here

一般情况下,对于绘制树形图,您可能会发现以下quick introduction对dendextend很有用(或查看more lengthy version)。