使用现有列的树状图的颜色分支

时间:2014-04-27 20:35:34

标签: r cluster-analysis hierarchical-clustering dendrogram dendextend

我有一个数据框,我正在尝试聚类。我现在正在使用hclust。在我的数据框中,有一个FLAG列,我想通过它为树形图着色。通过结果图片,我试图找出各种FLAG类别之间的相似之处。我的数据框看起来像这样:

FLAG    ColA    ColB    ColC    ColD

我正在colAcolBcolCcolD进行群集。我想对这些进行聚类并根据FLAG类别对它们进行着色。 Ex - 如果为1则为红色,如果为0则为蓝色(我只有两个类别)。现在我正在使用集群绘图的vanilla版本。

hc<-hclust(dist(data[2:5]),method='complete')
plot(hc)

在这方面的任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:2)

如果你想根据某个变量为树形图的分支着色,那么下面的代码(主要取自dendrapply函数的帮助)应该给出所需的结果:

x<-1:100
dim(x)<-c(10,10)
groups<-sample(c("red","blue"), 10, replace=TRUE)

x.clust<-as.dendrogram(hclust(dist(x)))

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 <- groups
  i <- 0
})

x.clust.dend <- dendrapply(x.clust, colLab)
plot(x.clust.dend)

答案 1 :(得分:2)

我认为Arhopala的答案很好。我冒昧地向前迈出了一步,并将函数assign_values_to_leaves_edgePar添加到 dendextend 包中(从版本0.17.2开始,即now on github) 。这个版本的功能从Arhopala的答案中得到了更强大和灵活,因为:

  1. 这是一个可以在不同的问题/设置中工作的一般功能
  2. 该函数可以处理其他edgePar参数(col,lwd,lty)
  3. 该功能提供部分病媒的回收,并在需要时提供各种警告按摩。
  4. 要安装 dendextend 包,您可以使用install.packages('dendextend'),但是对于最新版本,请使用以下代码:

    require2 <- function (package, ...) {
        if (!require(package)) install.packages(package); library(package)
    }
    
    ## require2('installr')
    ## install.Rtools() # run this if you are using Windows and don't have Rtools installed (you must have it for devtools)
    
    # Load devtools:
    require2("devtools")
    devtools::install_github('talgalili/dendextend')
    

    现在我们已经安装了dendextend,这是对Arhopala的第二个回答:

    x<-1:100
    dim(x)<-c(10,10)
    set.seed(1)
    groups<-sample(c("red","blue"), 10, replace=TRUE)
    x.clust<-as.dendrogram(hclust(dist(x)))
    
    x.clust.dend <- x.clust
    x.clust.dend <- assign_values_to_leaves_edgePar(x.clust.dend, value = groups, edgePar = "col") # add the colors.
    x.clust.dend <- assign_values_to_leaves_edgePar(x.clust.dend, value = 3, edgePar = "lwd") # make the lines thick
    plot(x.clust.dend)
    

    结果如下:

    enter image description here

    p.s:我个人更喜欢using pipes这种类型的编码(它会产生与上面相同的结果,但更容易阅读):

    x.clust <- x %>% dist  %>% hclust %>% as.dendrogram
    x.clust.dend <- x.clust %>% 
       assign_values_to_leaves_edgePar(value = groups, edgePar = "col") %>% # add the colors.
       assign_values_to_leaves_edgePar(value = 3, edgePar = "lwd") # make the lines thick
    plot(x.clust.dend)