基于节点位置的缠结图中的着色线

Coloring lines in tanglegram based on position of nodes

我正在使用以下代码创建缠结图:

library(ggtree)
library(ape)

tree1 <- read.tree(text='(((A:4.2,B:4.2):3.1,C:7.3):6.3,D:13.6);')
tree2 <- read.tree(text='(((B:4.2,A:4.2):3.1,C:7.3):6.3,D:13.6);')

p1 <- ggtree(tree1)
p2 <- ggtree(tree2)

d1 <- p1$data
d2 <- p2$data

d2$x <- max(d2$x) - d2$x + max(d1$x) + 1

pp <- p1 + geom_tree(data=d2)

dd <- bind_rows(d1, d2) %>% 
  filter(!is.na(label))

final_plot <- pp + geom_line(aes(x, y, group=label), data=dd, color='grey')

我想做的是根据节点的位置给线条上色。换句话说,如果这条线是直的,意味着它们在两棵树中的位置相同,则颜色应为x,而如果它们发生变化,则应为y。

像这样:

最好能有一个图例来解释颜色。

您可以在 dd 中构建一个列来检查线条是否水平。在这里,我按标签分组并检查唯一 ID 的数量是否为 1。然后将该列用于该行 aes 中的 color 参数。

dd <- dd %>% group_by(label) %>% mutate(is.horiz = n_distinct(node) == 1)
pp + 
  geom_line(aes(x, y, group=label, color = is.horiz), data=dd) +
  scale_color_manual(values = c('TRUE' = "lightblue", 'FALSE' = "purple")) +
  theme(legend.position = c(.9,.9)) +
  labs(color = 'Horizontal Nodes')

您可以随意调整线条的颜色和所有内容的名称。