手动创建树状图

时间:2019-04-18 16:07:45

标签: r dendrogram

我正在尝试通过不通过hclust或任何其他方式获得的相似性分数来创建树状图。我有两个分支,只想根据它们的相似程度将它们绘制出来,然后将它们分支。

A和B相似为0.5 A是0.2唯一 B是0.3唯一

所以A的总高度为0.7,B的总高度为0.8,其中0.5个分支是共享的。

以下内容仅创建两个分支,而没有连接两个叶子的长分支。有this similar question,但效果不佳!

x <- list(1, 2)
## attach "leaf" and "label" attributes to leaf nodes
attr(x[[1]], "leaf") <- TRUE
attr(x[[2]], "leaf") <- TRUE
attr(x[[1]], "label") <- "A"
attr(x[[2]], "label") <- "B"

## set "height" attributes for all nodes
attr(x, "height") <- 1
attr(x[[1]], "height") <- (1-0.7)
attr(x[[2]], "height") <- (1-0.8)

## set "midpoints" attributes for all nodes
attr(x, "midpoint") <- 1
attr(x[[1]], "midpoint") <- 0.5
attr(x[[2]], "midpoint") <- 0.5

## set "members" attributes for all nodes
attr(x, "members") <- 2
attr(x[[1]], "members") <- 1
attr(x[[2]], "members") <- 1

## set class as "dendrogram" 
class(x) <- "dendrogram"
x
plot(x)

1 个答案:

答案 0 :(得分:0)

您可以创建一个函数来构建叶子。添加属性的高度和总高度。 n和n1是您的A和B的叶子,n2是您的叶子的组合,并通过更改类将其转换为树状图。

Attr = function(o, plus_) {
        if (!missing(plus_)) for (n in names(plus_)) { attr(o, n) = plus_[[n]]; }
        o
}

n = Attr("A", list(label = "A", members = 1, height = 0.2, leaf = T));
n1 = Attr("B", list(label = "B", members = 1, height = 0.3, leaf = T));

n2 = Attr(list(n, n1), list(members = 2, height = 1, midpoint = 0.5));
class(n2) = 'dendrogram';
plot(n2)