关于 r:Change Dendrogram 叶子 | 珊瑚贝

Change Dendrogram leaves


我想修改从 hclust 对象的绘图生成的树状图中叶子的属性。最低限度,我想更改颜色,但您可以提供的任何帮助将不胜感激。

我确实尝试用谷歌搜索答案,但我看到的每一个解决方案似乎都比我想象的要困难得多。


不久前,Joris Meys 好心地向我提供了这段改变树叶颜色的代码片段。修改它以反映您的属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
clusDendro <- as.dendrogram(Clustering)
labelColors <- c(“red”,”blue”,”darkgreen”,”darkgrey”,”purple”)

## function to get colorlabels
colLab <- function(n) {
   if(is.leaf(n)) {
       a <- attributes(n)
       # clusMember – a vector designating leaf grouping
       # labelColors – a vector of colors for the above grouping
       labCol <- labelColors[clusMember[which(names(clusMember) == a$label)]]
       attr(n,”nodePar”) <- c(a$nodePar, lab.col = labCol)
   }
   n
}

## Graph
clusDendro <- dendrapply(clusDendro, colLab)
op <- par(mar = par(“mar”) + c(0,0,0,2))
plot(clusDendro,
     main =”Major title”,
     horiz = T, type =”triangle”, center = T)

par(op)

  • 请注意:如果您想更改标签,只需在 colLab 中返回与 n 不同的内容(也许很明显,但我记得花了一个下午才意识到这一点!)


这里有一个解决这个问题的方法,它使用了一个名为 “dendextend” 的新包,专为这类事情而构建。

您可以在以下 URL 的”使用”部分的演示文稿和小插图中看到许多示例:https://github.com/talgalili/dendextend

这是这个问题的解决方案:

1
2
3
4
5
6
7
8
# define dendrogram object to play with:
dend <- as.dendrogram(hclust(dist(USArrests[1:3,]),”ave”))
# loading the package
install.packages(‘dendextend’) # it is now on CRAN
library(dendextend)# let’s add some color:
labels_colors(dend) <- 2:4
labels_colors(dend)
plot(dend)

enter




来源:https://www.codenong.com/4720307/

微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?