简体   繁体   English

R 中按组划分的树状图的颜色分支(没有 h 或 k 元素)

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

I want to color branches of a dendrogram by specific groups that a defined in a dataframe.我想按 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)

That only colors the branches red.那只有 colors 的树枝是红色的。 Why?为什么? How can I solve that我该如何解决在此处输入图像描述

EDIT: It works when I do this编辑:当我这样做时它有效

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")

Just for future readers.只为未来的读者。 But actually I can´t color the dendrogram in an analog way.但实际上我无法以模拟方式为树状图着色。 I do not have a k or h element for defining clusters.我没有用于定义集群的kh元素。 Like in iris, I have predefined clusters I want to color.就像在 iris 中一样,我已经预定义了要着色的集群。

You should use the library dendextend .您应该使用库dendextend It has the functions for extending dendrogram objects.它具有扩展树状图对象的功能。

Below a simple example.下面是一个简单的例子。

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

dend_var is aa dendrogram or hclust tree object. dend_var是一个树状图或 hclust 树 object。

k is used to choose the number of groups. k用于选择组数。

h is used to choose the height at which to cut tree. h用于选择砍树的高度。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM