您可以将hclust
对象转换为 adendrogram
并用于?dendrapply
修改每个节点的属性(颜色、标签等属性),例如:
## stupid toy example
samples <- matrix(c(1, 1, 1,
2, 2, 2,
5, 5, 5,
6, 6, 6), byrow=TRUE, nrow=4)
## set sample IDs to A-D
rownames(samples) <- LETTERS[1:4]
## perform clustering
distSamples <- dist(samples)
hc <- hclust(distSamples)
## function to set label color
labelCol <- function(x) {
if (is.leaf(x)) {
## fetch label
label <- attr(x, "label")
## set label color to red for A and B, to blue otherwise
attr(x, "nodePar") <- list(lab.col=ifelse(label %in% c("A", "B"), "red", "blue"))
}
return(x)
}
## apply labelCol on all nodes of the dendrogram
d <- dendrapply(as.dendrogram(hc), labelCol)
plot(d)

编辑:为您的最小示例添加代码:
sample = data.frame(matrix(floor(abs(rnorm(20000)*100)),ncol=200))
groupCodes <- c(rep("A",25), rep("B",25), rep("C",25), rep("D",25))
## make unique rownames (equal rownames are not allowed)
rownames(sample) <- make.unique(groupCodes)
colorCodes <- c(A="red", B="green", C="blue", D="yellow")
## perform clustering
distSamples <- dist(sample)
hc <- hclust(distSamples)
## function to set label color
labelCol <- function(x) {
if (is.leaf(x)) {
## fetch label
label <- attr(x, "label")
code <- substr(label, 1, 1)
## use the following line to reset the label to one letter code
# attr(x, "label") <- code
attr(x, "nodePar") <- list(lab.col=colorCodes[code])
}
return(x)
}
## apply labelCol on all nodes of the dendrogram
d <- dendrapply(as.dendrogram(hc), labelCol)
plot(d)
