简体   繁体   中英

How do I add a legend to a facet in ggtree's `facet_plot`?

I am using facet_plot() to add a barplot with trait values next to the tips of my tree. I need there to be a legend for the barplot, but could not find in the documentation or in a similar question how to do that. It seems that facet_plot() makes this a bit trickier.

Here is my code:

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")

特征数据映射到提示的随机树

I've tried to add + guides(fill = guide_legend()) or + scale_fill_discrete() , but to no avail.

How can I add a legend to the Trait facet? (And, in extension, to any additional facet?)

We can add theme(legend.position="bottom") to get desired plot.

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")

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM