wilkelab / cowplot

cowplot: Streamlined Plot Theme and Plot Annotations for ggplot2
https://wilkelab.org/cowplot/
704 stars 84 forks source link

get_legend doesn't match original position #186

Open cliffbueno opened 2 years ago

cliffbueno commented 2 years ago

Hello,

Thanks for a great package! I noticed the following issue.

When making a plot with ggplot, setting theme(legend.position = "right) centers the legend vertically with respect to the data portion of the plot, not the whole panel area, which is what ends up happening in plot_grid. This can be seen in the example from the get_legend vignette. Adding a legend separately with get_legend works well to enable aligning the plots vertically, but notice that the legend shifts downwards slightly in the cowplot. The legend title goes from being in the 35-40 hwy row to the 30-35 hwy row. This isn't a big deal here, but the same thing happens with a legend.position = "bottom" situation, where plot_grid puts the legend slightly to the left of the plot center in a way that is more noticeable and not aesthetically pleasing.

p1 <- ggplot(mtcars, aes(mpg, disp)) + geom_line()
plot.mpg <- ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) + geom_point(size=2.5)
# Note that these cannot be aligned vertically due to the legend in the plot.mpg
ggdraw(plot_grid(p1, plot.mpg, ncol=1, align='v'))

legend <- get_legend(plot.mpg)
plot.mpg <- plot.mpg + theme(legend.position='none')
# Now plots are aligned vertically with the legend to the right
ggdraw(plot_grid(plot_grid(p1, plot.mpg, ncol=1, align='v'),
                 plot_grid(NULL, legend, ncol=1),
                 rel_widths=c(1, 0.2)))