2

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

mpe
  • 1,000
  • 1
  • 8
  • 25

1 Answers1

2

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

markus
  • 25,843
  • 5
  • 39
  • 58
  • This doesn't seem to work if the legend is for the tree (and not the annotation). Works neither with `facet_plot` nor `geom_facet`. – Dunois Sep 01 '21 at 16:04
  • Addendum: actually works, but users trying this, please be warned, if you're going to use `ggtree::facet_widths`, locate the legend properly first beforehand. – Dunois Sep 01 '21 at 16:35