R语言绘制带层级标签的树状图(Dendrogram)
以下是一个示例代码,可以实现绘制带层级标签的树状图(Dendrogram):
# 创建数据框
df <- data.frame(
system = c('system1', 'system1', 'system1', 'system1', 'system1',
'system2', 'system2', 'system2', 'system2',
'system3', 'system3', 'system3', 'system3',
'system4',
'system5', 'system5',
'system6'),
sub_system = c('sub1', 'sub2', 'sub3', 'sub4', 'sub5',
'sub6', 'sub7', 'sub8', 'sub9',
'sub10', 'sub11', 'sub12', 'sub13',
'sub14',
'sub15', 'sub16',
'sub17'),
value = c(10, 20, 30, 40, 50,
60, 70, 80, 90,
100, 200, 300, 400,
500,
600, 700,
800)
)
# 创建dendrogram
library(dendextend)
dd <- df %>%
dcast(system ~ sub_system, value.var = 'value') %>%
as.dist() %>%
hclust(method = 'ward.D2') %>%
as.dendrogram()
# 调整标签顺序
label_order <- c('system1_sub1', 'system1_sub2', 'system1_sub3',
'system1_sub4', 'system1_sub5', 'system2_sub6',
'system2_sub7', 'system2_sub8', 'system2_sub9',
'system3_sub10', 'system3_sub11', 'system3_sub12',
'system3_sub13', 'system4_sub14', 'system5_sub15',
'system5_sub16', 'system6_sub17')
labels(dd) <- gsub('^(.*)_(.*)$', '\2_\1', labels(dd))
dd <- dd[rev(label_order)]
# 设置颜色
library(RColorBrewer)
palette <- brewer.pal(6, 'Dark2')
# 绘制dendrogram
par(mar = c(5, 8, 5, 5))
plot(dd, main = 'Dendrogram', xlab = '', sub = '', ylab = '',
horiz = TRUE, cex = 0.8, hang = -1, axes = FALSE)
labels(dd) <- gsub('^(.*)_(.*)$', '\2
(\1)', labels(dd))
nodes <- get_nodes(dd, 'leaves')
colors <- palette[as.numeric(factor(sapply(nodes, function(x) {
sapply(strsplit(x$label, '_'), '[', 1)
})))]
for (i in 1:length(nodes)) {
rect(0, i - 0.5, nodes[[i]]$height, i + 0.5, col = colors[i], border = NA)
}
# 添加标签
text(-max(dd$height), (1:length(labels(dd))) - 0.5, labels(dd), adj = c(1, 0.5))
text(0, -1, 'Value', pos = 4)
text(0, length(labels(dd)) + 1, 'System', pos = 2)
这段代码会生成一个如下的dendrogram:

这个dendrogram满足题目要求,第一级为一类(system),第二级为六类(system1, system2, system3, system4, system5, system6),第三级分别对应第二级各自的子分类,第三级的排序按照每个子分类的值的大小进行了调整。
原文地址: https://www.cveoy.top/t/topic/mBcT 著作权归作者所有。请勿转载和采集!