如何在 r 中以一种颜色为树状图上的相同标签着色
How to color the same labels on dendorgram in one colour in r
我在 r
中对一些数据进行了聚类,并将结果绘制为树状图。我现在想知道的是如何更改标签的颜色,以便相同的标签具有相同的颜色。
我使用以下代码得到了树状图:
> d<-stringdist::stringdistmatrix(AR_GenesforR$AR_Genes)
> cl <-hclust(as.dist(d))
> plot(cl, label=AR_GenesforR$AR_Genes)
> groups <- cutree(cl, k=2)
> rect.hclust(cl, k=2, border="red")
生成的树状图如下所示:
我现在想做的是给所有相同的标签涂上相同的颜色,例如。所有 2010
为黄色,所有 2011
为蓝色,依此类推。我已经研究了很多,但大多只找到了根据标签所在的簇为标签着色的方法。有人知道我如何做我想做的事吗?
这是一个函数,可以根据 dendextend R package (here is a short 2 page paper on the package).
执行您的要求
x <- c(2011,2011,2012,2012,2015,2015,2015)
names(x) <- x
dend <- as.dendrogram(hclust(dist(x)))
color_unique_labels <- function(dend, ...) {
if(!require(dendextend)) install.packages("dendextend")
if(!require(colorspace)) install.packages("colorspace")
library("dendextend")
n_unique_labels <- length(unique(labels(dend)))
colors <- colorspace::rainbow_hcl(n_unique_labels)
labels_number <- as.numeric(factor(labels(dend)))
labels_colors(dend) <- colors[labels_number]
dend
}
par(mfrow = c(1,2))
plot(dend)
dend2 <- color_unique_labels(dend)
plot(dend2)
我在 r
中对一些数据进行了聚类,并将结果绘制为树状图。我现在想知道的是如何更改标签的颜色,以便相同的标签具有相同的颜色。
我使用以下代码得到了树状图:
> d<-stringdist::stringdistmatrix(AR_GenesforR$AR_Genes)
> cl <-hclust(as.dist(d))
> plot(cl, label=AR_GenesforR$AR_Genes)
> groups <- cutree(cl, k=2)
> rect.hclust(cl, k=2, border="red")
生成的树状图如下所示:
我现在想做的是给所有相同的标签涂上相同的颜色,例如。所有 2010
为黄色,所有 2011
为蓝色,依此类推。我已经研究了很多,但大多只找到了根据标签所在的簇为标签着色的方法。有人知道我如何做我想做的事吗?
这是一个函数,可以根据 dendextend R package (here is a short 2 page paper on the package).
执行您的要求x <- c(2011,2011,2012,2012,2015,2015,2015)
names(x) <- x
dend <- as.dendrogram(hclust(dist(x)))
color_unique_labels <- function(dend, ...) {
if(!require(dendextend)) install.packages("dendextend")
if(!require(colorspace)) install.packages("colorspace")
library("dendextend")
n_unique_labels <- length(unique(labels(dend)))
colors <- colorspace::rainbow_hcl(n_unique_labels)
labels_number <- as.numeric(factor(labels(dend)))
labels_colors(dend) <- colors[labels_number]
dend
}
par(mfrow = c(1,2))
plot(dend)
dend2 <- color_unique_labels(dend)
plot(dend2)