r - 如何通过 R 中的附加因子变量为树状图的标签着色

标签 r colors plot dendrogram dendextend

在使用以下代码在 R 中运行层次聚类分析后,我生成了一个树状图。我现在尝试根据另一个因子变量为标签着色,该变量保存为向量。我最接近实现这一目标的是使用 ColourDendrogram 对分支进行颜色编码。 sparcl 中的函数包裹。如果可能,我更愿意对标签进行颜色编码。我在以下链接中找到了类似问题的答案 Color branches of dendrogram using an existing column & Colouring branches in a dendrogram in R ,但我一直无法弄清楚如何为我的目的转换示例代码。下面是一些示例数据和代码。

> dput(df)
structure(list(labs = c("a1", "a2", "a3", "a4", "a5", "a6", "a7", 
"a8", "b1", "b2", "b3", "b4", "b5", "b6", "b7"), var = c(1L, 
1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L), td = c(13.1, 
14.5, 16.7, 12.9, 14.9, 15.6, 13.4, 15.3, 12.8, 14.5, 14.7, 13.1, 
14.9, 15.6, 14.6), fd = c(2L, 3L, 3L, 1L, 2L, 3L, 2L, 3L, 2L, 
4L, 2L, 1L, 4L, 3L, 3L)), .Names = c("labs", "var", "td", "fd"
), class = "data.frame", row.names = c(NA, -15L))

df.nw = df[,3:4]
labs = df$labs

d = dist(as.matrix(df.nw))                          # find distance matrix 
hc = hclust(d, method="complete")                   # apply hierarchical clustering 
plot(hc, hang=-0.01, cex=0.6, labels=labs, xlab="") # plot the dendrogram

hcd = as.dendrogram(hc)                             # convert hclust to dendrogram 
plot(hcd, cex=0.6)                                  # plot using dendrogram object

Var = df$var                                        # factor variable for colours
varCol = gsub("1","red",Var)                        # convert numbers to colours
varCol = gsub("2","blue",varCol)

# colour-code dendrogram branches by a factor 
library(sparcl)
ColorDendrogram(hc, y=varCol, branchlength=0.9, labels=labs,
                xlab="", ylab="", sub="")   

任何关于如何做到这一点的建议将不胜感激。

最佳答案

尝试

# ... your code
colLab <- function(n) {
  if(is.leaf(n)) {
    a <- attributes(n)
    attr(n, "label") <- labs[a$label]
    attr(n, "nodePar") <- c(a$nodePar, lab.col = varCol[a$label]) 
  }
  n
}
plot(dendrapply(hcd, colLab))

( via )

关于r - 如何通过 R 中的附加因子变量为树状图的标签着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27485549/

相关文章:

matlab - Matlab 中的双刻度标签

r - 在 linux 中为 R 安装 xgboost 时出错

r - 确定向量中是否存在元素的最有效方法

uitableview - 为什么 UITableView 会忽略带有自定义 separatorInset 的 "extra"分隔符的 separatorColor?

pdf - 使用 Ghostscript 替换 PDF 中的颜色

java - 从正在运行的应用程序窗口获取像素颜色 - JAVA

r - 当数据更改时,ggvis 中的 linked_brush 无法在 Shiny 中工作

r - 计算 r 中后跟单独字符串出现次数的字符串

R:将数据集分割为四分位数/十分位数。正确的方法是什么?

r - 如何使用文本绘制水平而不是因子变量 rpart 的标签/索引?