如何在树形图中突出显示特定标签?

时间:2014-04-14 21:54:37

标签: r dendrogram hclust dendextend

我使用简单的以下代码进行了聚类分析

hc2 = hclust(dist(geno.imp))
pdf(file="file.pdf", width=50)
plot(hc2,cex=0.2) 
dev.off()

我想强调一些特定的叶子(不是节点)。我在单独的向量中有这些叶子的列表。如何仅突出显示特定叶子,将所有其他叶子保持黑色?

2 个答案:

答案 0 :(得分:2)

看看?dendrapplydendrapply允许您将函数应用于dendrogram的每个节点。在该函数中,您可以更改节点的属性,例如:

## create some example data
set.seed(1)
highlight <- rownames(USArrests)[sample(nrow(USArrests), 10)]

## function to change color etc. of a leaf
colorLeafs <- function(x) {
  if (is.leaf(x) && attr(x, "label") %in% highlight) {
    attr(x, "nodePar") <- list(lab.col="red", pch=NA)
  }
  return(x)
}

hc <- hclust(dist(USArrests), "ave")

dd <- dendrapply(as.dendrogram(hc), colorLeafs)

plot(dd)

enter image description here

答案 1 :(得分:2)

对于特定情况,sgibb答案是一个很好的答案。您还可以尝试使用dendextend包,专为此类设计。

以下两种方法可以获得与sgibb示例相同的结果:

dend <- as.dendrogram(hclust(dist(USArrests), "ave"))
## create some example data
set.seed(1)
highlight <- rownames(USArrests)[sample(nrow(USArrests), 10)]

install.packages("dendextend")
library(dendextend)
# create a dendrogram with colored labels:
dend2 <- color_labels(dend, labels = highlight , col = 2) 
# ploting it
plot(dend2)

# Here is a second way for doing the same thing:
dend2 <- color_labels(dend, col = ifelse(labels(dend) %in% highlight, 2, 1)) 
plot(dend2)

enter image description here