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

R and rect.hclust: rectangle on labels in dendrograms

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

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

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")

下面是上面代码的情节:

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

谢谢!

您应该使用 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")

你会得到:

通常,对于绘制树状图,您可能会发现以下 quick introduction to dendextend useful (or look at the more lengthy version)。