Search code examples
rggplot2ggtree

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

Random tree with trait data mapped to tips

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


Solution

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

    enter image description here