簡體   English   中英

使用現有列的樹狀圖的顏色分支

[英]Color branches of dendrogram using an existing column

我有一個數據框,我試圖集群。 我現在正在使用hclust 在我的數據框中,有一個FLAG列,我想通過它為樹形圖着色。 根據結果​​,我試圖找出各種FLAG類別之間的相似之處。 我的數據框看起來像這樣:

FLAG    ColA    ColB    ColC    ColD

我正在聚集colAcolBcolCcolD 我想根據FLAG類別對這些進行聚類並着色。 Ex - 如果為1則為紅色,如果為0則為藍色(我只有兩個類別)。 現在我正在使用群集繪圖的vanilla版本。

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

在這方面的任何幫助將受到高度贊賞。

如果要根據某個變量為樹形圖的分支着色,那么下面的代碼(主要取自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)

我認為Arhopala的答案很好。 我冒昧地向前邁出了一步,並將函數assign_values_to_leaves_edgePar添加到dendextend包中(從版本0.17.2開始, 現在在github上 )。 從Arhopala的答案開始,這個版本的功能更加強大和靈活:

  1. 它是一個通用功能,可以在不同的問題/設置中工作
  2. 該函數可以處理其他edgePar參數(col,lwd,lty)
  3. 該功能提供部分病媒的回收,並在需要時提供各種警告按摩。

要安裝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)

結果如下:

在此輸入圖像描述

ps:我個人更喜歡使用管道進行這種類型的編碼(這將產生與上面相同的結果,但更容易閱讀):

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM