如何在ggtree的`facet_plot`中将图例添加到构面?

时间:2019-06-27 11:01:10

标签: r ggplot2 ggtree

我正在使用facet_plot()在树的提示旁边添加带有特征值的条形图。我需要有一个关于图例的图例,但是在documentationa similar question中找不到如何做的图例。似乎facet_plot()有点棘手。

这是我的代码:

library(ggtree)
library(tidyverse)
library(ggstance) # for horizontal versions of geoms

# create some random tree and trait data
tree <- rtree(5)
traits <- tibble(
  node  = paste0("t", rep(1:5, 4)),
  trait = rep(LETTERS[1:4], 5),
  value = rnorm(n = 20, mean = 10, sd = 2))

# tree plot with barplot facet
treeplot <- ggtree(tree) + geom_tiplab(align = T)
facet_plot(treeplot,
           panel = "Trait",
           data = traits,
           geom = geom_barh,
           mapping = aes(x = value, fill = trait),
           stat = "identity")

Random tree with trait data mapped to tips

我尝试添加+ guides(fill = guide_legend())+ scale_fill_discrete(),但无济于事。

如何为“特质”构面添加图例? (而且,扩展到其他方面?)

1 个答案:

答案 0 :(得分:1)

我们可以添加theme(legend.position="bottom")以获得所需的图。

facet_plot(treeplot,
           panel = "Trait",
           data = traits,
           geom = geom_barh,
           mapping = aes(x = value, fill = trait),
           stat = "identity", show.legend = TRUE) +
  theme(legend.position = "bottom")

enter image description here