簡體   English   中英

R 中按組划分的樹狀圖的顏色分支(沒有 h 或 k 元素)

[英]color branches of dendrogram by groups in R (without h or k element)

我想按 dataframe 中定義的特定組對樹狀圖的分支進行着色。

library(reshape2)
library(factoextra) # clustering visualization 
library(dendextend)
#iris dataset
#defining colors
colori = rep(NA, length=length(iris$Species))
colori[which(iris$Species=="setosa")] = "red"
colori[which(iris$Species=="versicolor")] = "blue"
colori[which(iris$Species=="virginica")] = "yellow"

iris_dist <- dist(iris[ ,1:4],)
hc1_iris <- hclust(iris_dist,method = "average")
col_dendro_iris <- color_branches(as.dendrogram(hc1_iris),groupLabels =T, clusters = iris$Species,col=colori)

col_dendro_iris_plot <- plot(col_dendro_iris,main = "Dendrogram of normalized BLS\ncolored by manmade groups",labels = NULL,xlab = NULL)

那只有 colors 的樹枝是紅色的。 為什么? 我該如何解決在此處輸入圖像描述

編輯:當我這樣做時它有效

pca_iris <- PCA(iris[ ,1:4])
colori = rep(NA, length=length(iris$Species))
colori[which(iris$Species=="versicolor")] = "red"
colori[which(iris$Species=="virginica")] = "yellow"
colori[which(iris$Species=="setosa")] = "blue"
# species <- iris$Species
iris_gr <- cbind(iris,colori)
# 
pca_iris <- fviz_pca_ind(pca_iris,
             pointshape = 21,habillage = iris$Species,
             geom.ind = c("point"),geom = c("point"),palette = iris$colori,
             title="PCA of normalized BLS\ncolored by manmade groups")
pca_iris<- pca_iris + theme(legend.position = "upper.right")

只為未來的讀者。 但實際上我無法以模擬方式為樹狀圖着色。 我沒有用於定義集群的kh元素。 就像在 iris 中一樣,我已經預定義了要着色的集群。

您應該使用庫dendextend 它具有擴展樹狀圖對象的功能。

下面是一個簡單的例子。

library(dendextend)
dend_var<-as.dendrogram(hc_var)
dend_colored<-color_branches(dend_var, h=10000, k=7)
plot(dend_colored)

dend_var是一個樹狀圖或 hclust 樹 object。

k用於選擇組數。

h用於選擇砍樹的高度。

在此處輸入圖像描述

暫無
暫無

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

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