[英]Color branches of dendrogram using an existing column
我有一個數據框,我試圖集群。 我現在正在使用hclust
。 在我的數據框中,有一個FLAG
列,我想通過它為樹形圖着色。 根據結果,我試圖找出各種FLAG
類別之間的相似之處。 我的數據框看起來像這樣:
FLAG ColA ColB ColC ColD
我正在聚集colA
, colB
, colC
和colD
。 我想根據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的答案開始,這個版本的功能更加強大和靈活:
要安裝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.