Placing the legend above the main title in ggplot2
when using theme(legend.position = "top")
seemed to be the default (and unwanted) outcome in previous versions of ggplot: ggplot legend at top but below title?
In the current version of ggplot2
, the legend places itself between the plot and the main title when setting theme(legend.position = "top")
. A small example:
d <- data.frame(x = 1:2, y = 1:2, z = c("a", "b"))
ggplot(d, aes(x = x, y = y, fill = z)) +
geom_col() +
ggtitle("My title") +
theme(legend.position = "top")
How can I place the legend above main title?
Or we can create a fake facet and put the plot title in it. After that do some tweaking to remove the strip facet and reduce the legend margin
Created on 2018-10-12 by the reprex package (v0.2.1.9000)
This requires a little more work than adjusting margins, but it should allow for more control over placement and sizing. I'm using functions from
cowplot
:get_legend
to extract the legend from the plot, andplot_grid
to create a grid of these twoggplot
elements.After creating the plot
p
with a legend,cowplot::get_legend(p)
then creates aggplot
object that is just the legend. Reposition them withplot_grid
while adding atheme
call that removes the legend fromp
. You'll probably want to tweak the heights and perhaps adjust margins.Created on 2018-10-12 by the reprex package (v0.2.1)
There are other ways as well, but this was the easiest one that came to mind.