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