在 r 中的 geom_bar 旁边的 ggtree 中添加家庭注释

Add families annotation to ggtree next to geom_bar in r

我需要帮助才能在情节中添加信息。

剧情如下:

(获取此图的代码如下)

我想添加一个新元素,其中包含存储在此 选项卡中的家庭信息:

   labels     family
1      t2  Hominidae
2      t4  Hominidae
3      t3  Hominidae
4     t10    Equidae
5      t5    Equidae
6      t7  Muridae
7      t6    Muridae
8      t1 Crisetidae
9      t8 Crisetidae
10     t9   Outgroup

(输入格式)

structure(list(labels = c("t2", "t4", "t3", "t10", "t5", "t7", 
"t6", "t1", "t8", "t9"), family = c("Hominidae", "Hominidae", 
"Hominidae", "Equidae", "Equidae", "Murinidae", "Muridae", "Crisetidae", 
"Crisetidae", "Outgroup")), class = "data.frame", row.names = c(NA, 
-10L))

并得到一个新数字,例如 ;

如您所见,我利用存储在 选项卡 中的信息为每个 labels 添加竖线,后跟 family 的名称.

我发现这个 post 相关的 (http://www.randigriffin.com/2017/05/11/primate-phylogeny-ggtree.html) ,但它没有用 geom_bars 做,它只是在树标签旁边添加家庭注释...

   library(ggplot2)
library(ggtree)

set.seed(2019-10-31)
tr <- rtree(10)

d1 <- data.frame(
  # only some labels match
  label = c(tr$tip.label[sample(9, 9)], "A"),
  value = sample(1:10, 10))

d2 <- data.frame(
  label = rep(tr$tip.label, 5),
  category = rep(LETTERS[1:5], each=10),
  value = rnorm(50, 0, 3)) 

g <- ggtree(tr) + geom_tiplab(align=TRUE) + hexpand(.01)

d2$label <- factor(d2$label, levels = rev(get_taxa_name(g)))
d1$label <- factor(d1$label, levels = rev(get_taxa_name(g)))

p1 <- ggplot(d1, aes(label, value)) + geom_col(aes(fill=label)) + 
  geom_text(aes(label=label, y= value+.1)) +
  coord_flip() + theme_tree2() + theme(legend.position='none')

p2 <- ggplot(d2, aes(x=category, y=label)) + 
  geom_tile(aes(fill=value)) + scale_fill_viridis_c() + 
  theme_minimal() + xlab(NULL) + ylab(NULL)+ theme(legend.position='none')


cowplot::plot_grid(g, p2, p1, ncol=3) 

使用 left_join 和构面:

d1 <- dplyr::left_join(d1, tab, by = c(label = "labels"))

p1 <- ggplot(d1, aes(label, value)) + geom_col(aes(fill=label)) + 
  geom_text(aes(label=label, y= value+.1)) +
  coord_flip() + theme_tree2() + theme(legend.position='none') +
  facet_grid(family~., scales = "free_y", space = "free_y") +
  scale_x_discrete(expand = c(0, 0), position = "top") +
  theme(plot.margin = margin(10, 10, 10, 0),
        axis.line.y.right = element_line(size = 3),
        strip.background = element_blank(),
        strip.placement = "outside")

p2 <- ggplot(d2, aes(x=category, y=label)) + 
  geom_tile(aes(fill=value)) + 
  scale_fill_viridis_c() + 
  theme_minimal() + 
  xlab(NULL) + 
  ylab(NULL)+ 
  theme(legend.position='none')


cowplot::plot_grid(g, p2, p1, ncol=3)