2

这是我的数据

df<- structure(list(name = structure(c(2L, 12L, 1L, 16L, 14L, 10L, 
9L, 5L, 15L, 4L, 8L, 13L, 7L, 6L, 3L, 11L), .Label = c("All", 
"Bab", "boro", "bra", "charli", "delta", "few", "hora", "Howe", 
"ist", "kind", "Kiss", "myr", "No", "TT", "where"), class = "factor"), 
    value = c(1.251, -1.018, -1.074, -1.137, 1.018, 1.293, 1.022, 
    -1.008, 1.022, 1.252, -1.005, 1.694, -1.068, 1.396, 1.646, 
    1.016)), .Names = c("name", "value"), class = "data.frame", row.names = c(NA, 
-16L))

我在这里做什么

d <- dist(as.matrix(df$value),method = "euclidean")
#compute cluster membership
hcn <- hclust(d,method = "ward.D2")
plot(hcn)

它给了我我想要的如下在此处输入图像描述

这里所有组都用黑色显示,并且树状图不是很清楚我想要的是更改每个组的颜色并使用垂直名称而不是数字,最后我希望能够移除 hclust( " ward.D2") 同时根据需要更改 x 标签和 y 标签

4

2 回答 2

4

您可以使用 dendextend 包,针对以下任务:

# install the package:

if (!require('dendextend')) install.packages('dendextend'); 图书馆('dendextend')

## Example:
dend <- as.dendrogram(hclust(dist(USArrests), "ave"))
d1=color_branches(dend,k=5, col = c(3,1,1,4,1))
plot(d1) # selective coloring of branches :)
d2=color_branches(d1,k=5) # auto-coloring 5 clusters of branches.
plot(d2)
# More examples are in ?color_branches

在此处输入图像描述

您可以在以下 URL 的“使用”部分中的演示文稿和小插图中看到许多示例:https ://github.com/talgalili/dendextend

或者你也可以使用:

你应该使用 dendrapply。

例如:

# Generate data
set.seed(12345)
desc.1 <- c(rnorm(10, 0, 1), rnorm(20, 10, 4))
desc.2 <- c(rnorm(5, 20, .5), rnorm(5, 5, 1.5), rnorm(20, 10, 2))
desc.3 <- c(rnorm(10, 3, .1), rnorm(15, 6, .2), rnorm(5, 5, .3))

data <- cbind(desc.1, desc.2, desc.3)

# Create dendrogram
d <- dist(data) 
hc <- as.dendrogram(hclust(d))

# Function to color branches
colbranches <- function(n, col)
  {
  a <- attributes(n) # Find the attributes of current node
  # Color edges with requested color
  attr(n, "edgePar") <- c(a$edgePar, list(col=col, lwd=2))
  n # Don't forget to return the node!
  }

# Color the first sub-branch of the first branch in red,
# the second sub-branch in orange and the second branch in blue
hc[[1]][[1]] = dendrapply(hc[[1]][[1]], colbranches, "red")
hc[[1]][[2]] = dendrapply(hc[[1]][[2]], colbranches, "orange")
hc[[2]] = dendrapply(hc[[2]], colbranches, "blue")

# Plot
plot(hc)

我从以下获得此信息:如何创建带有彩色分支的树状图?

于 2016-08-11T09:11:48.410 回答
1

我们可以改为围绕组绘制矩形,假设有 5 个组(k = 5):

# plot dendogram
plot(hcn)

# then draw dendogram with red borders around the 5 clusters 
rect.hclust(hcn, k = 5, border = "red")

在此处输入图像描述


编辑:

删除 x 轴标签,并添加名称而不是数字:

plot(hcn, xlab = NA, sub = NA, labels = df$name)
rect.hclust(hcn, k = 5, border = "red")

在此处输入图像描述

于 2016-08-11T09:54:51.480 回答