gpt4 book ai didi

r - R中树状图中的着色分支

转载 作者:行者123 更新时间:2023-12-04 20:03:38 26 4
gpt4 key购买 nike

亲爱的居民 R 天才,

我想在没有标记叶子的树状图中为簇的分支着色。

我在 Stackoverflow 上找到了以下脚本:

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)

我已经尝试如下调整它以适应我的数据,但没有成功。

Gdis.UPGMA<-hclust(Gdis, method = "average", members=NULL)
k<-12
Gdiswo<-reorder.hclust(Gdis.UPGMA, Gdis, labels = FALSE)
cutg <- cutree(Gdiswo, k=k)

clusDendro <- as.dendrogram(Gdiswo)
labelColors <- c("red", "blue", "darkgreen", "darkgrey", "purple")

## function to get colorlabels
colLab <- function(n) {
   if(is.leaf(n)) {
       a <- attributes(n)
       # cutg - a vector designating leaf grouping
       # labelColors - a vector of colors for the above grouping
       labCol <- labelColors[cutg[which(names(cutg) == 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)

我怀疑是 n 导致了问题,但我不确定应该用什么代替 n。由于论文截止日期迫在眉睫,我将不胜感激任何建议。谢谢,-伊丽莎白

最佳答案

您需要设置树状图对象的edgePar元素。

?dendrapply 的帮助中有一个设置节点标签颜色的示例。通过仅更改一行以指向 "edgePar" 并设置 col,您就快完成了:

attr(n, "edgePar") <- c(a$nodePar, list(col = mycols[i], lab.font= i%%3))

完整修改示例:

## a smallish simple dendrogram
dhc <- as.dendrogram(hc <- hclust(dist(USArrests), "ave"))

## toy example to set colored leaf labels :
local({
colLab <<- function(n) {
if(is.leaf(n)) {
a <- attributes(n)
i <<- i+1
attr(n, "edgePar") <-
c(a$nodePar, list(col = mycols[i], lab.font= i%%3))
}
n
}
mycols <- grDevices::rainbow(attr(dhc21,"members"))
i <- 0
})
dL <- dendrapply(dhc21, colLab)
plot(dL) ## --> colored labels

enter image description here


您可以通过仔细研究 ?dendrapply?as.dendrogram 阅读所有关于这样做的内容

关于r - R中树状图中的着色分支,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10571266/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com