![](/img/trans.png)
[英]Rotating labels within a dendrogram object and changing the default dendrogram colour (R)
[英]How to colour the labels of a dendrogram by an additional factor variable in R
我使用下面的代碼在R中運行層次聚類分析后生成了一個樹形圖。 我現在嘗試根據另一個因子變量為標簽着色,該變量保存為矢量。 我實現這一目標的最接近的方法是使用sparcl
包中的ColourDendrogram
函數對分支進行顏色編碼。 如果可能的話,我更願意對標簽進行顏色編碼。 我在以下鏈接中找到了類似問題的答案在樹形圖中使用現有列和着色分支的樹形圖的 顏色分支 ,但是我還沒有能夠找到如何為我的目的轉換示例代碼。 下面是一些示例數據和代碼。
> dput(df)
structure(list(labs = c("a1", "a2", "a3", "a4", "a5", "a6", "a7",
"a8", "b1", "b2", "b3", "b4", "b5", "b6", "b7"), var = c(1L,
1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L), td = c(13.1,
14.5, 16.7, 12.9, 14.9, 15.6, 13.4, 15.3, 12.8, 14.5, 14.7, 13.1,
14.9, 15.6, 14.6), fd = c(2L, 3L, 3L, 1L, 2L, 3L, 2L, 3L, 2L,
4L, 2L, 1L, 4L, 3L, 3L)), .Names = c("labs", "var", "td", "fd"
), class = "data.frame", row.names = c(NA, -15L))
df.nw = df[,3:4]
labs = df$labs
d = dist(as.matrix(df.nw)) # find distance matrix
hc = hclust(d, method="complete") # apply hierarchical clustering
plot(hc, hang=-0.01, cex=0.6, labels=labs, xlab="") # plot the dendrogram
hcd = as.dendrogram(hc) # convert hclust to dendrogram
plot(hcd, cex=0.6) # plot using dendrogram object
Var = df$var # factor variable for colours
varCol = gsub("1","red",Var) # convert numbers to colours
varCol = gsub("2","blue",varCol)
# colour-code dendrogram branches by a factor
library(sparcl)
ColorDendrogram(hc, y=varCol, branchlength=0.9, labels=labs,
xlab="", ylab="", sub="")
任何關於如何做到這一點的建議將不勝感激。
嘗試
# ... your code
colLab <- function(n) {
if(is.leaf(n)) {
a <- attributes(n)
attr(n, "label") <- labs[a$label]
attr(n, "nodePar") <- c(a$nodePar, lab.col = varCol[a$label])
}
n
}
plot(dendrapply(hcd, colLab))
( 通過 )
要使標簽着色,最容易使用dendextend包中的labels_colors
函數。 例如:
# install.packages("dendextend")
library(dendextend)
small_iris <- iris[c(1, 51, 101, 2, 52, 102), ]
dend <- as.dendrogram(hclust(dist(small_iris[,-5])))
# Like:
# dend <- small_iris[,-5] %>% dist %>% hclust %>% as.dendrogram
# By default, the dend has no colors to the labels
labels_colors(dend)
par(mfrow = c(1,2))
plot(dend, main = "Original dend")
# let's add some color:
colors_to_use <- as.numeric(small_iris[,5])
colors_to_use
# But sort them based on their order in dend:
colors_to_use <- colors_to_use[order.dendrogram(dend)]
colors_to_use
# Now we can use them
labels_colors(dend) <- colors_to_use
# Now each state has a color
labels_colors(dend)
plot(dend, main = "A color for every Species")
有關包裝的更多詳細信息,您可以查看其小插圖 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.