'Whitespace and overlapping legends in ggplot2 multi-plot-arrangement
So I have several plots I would like to arrange together with their legends and these legends should be in the bottom row and only once per plot type (check the reprex below, its not so easy to verbalize :-/).
reprex pt1: make plots and get legends
library(ggplot2)
library(gridExtra)
data(iris)
### make some plots
small.1<-ggplot(iris)+
geom_point(aes(x=Sepal.Length, y=Sepal.Width, color=Species, size=Petal.Width))+
theme(legend.position="none")
small.2<-ggplot(iris)+
geom_point(aes(x=Petal.Length, y=Petal.Width, color=Species, size=Petal.Length))+
theme(legend.position="none")
big<-ggplot(iris)+
geom_boxplot(aes(x=Species, y=Sepal.Length*Petal.Length, fill=Species))+
theme(legend.position="none")
### get the legneds
small.leg<-get_legend(small.1+theme(legend.position="bottom")+guides(color=guide_legend(title.positon="top")))
big.leg<-get_legend(big+theme(legend.position="bottom")+guides(fill=guide_legend(title.positon="top")))
Then I arranged them into a matrix with marrangeGrob. I tried various versions with plot_grid but that turns out horribly bc. I have to specify rel_heights/widths and the legends don't really align...
reprex pt2 marrangeGrob
### make a layout matrix
layout_mat<-rbind(c(1,2,2),
c(3,2,2),
c(4,NA,5))
### combine plots into list (list order like order in matrix)
iris.list<-list(small.1, big, small.2, small.leg, big.leg)
### arrange
iris.arrange<-marrangeGrob(iris.list, layout_matrix=layout_mat)
Q: How do I get rid of the whitespace between plots and legends?
Solution 1:[1]
I don't know how to reduce the whitespace with the marrangeGrob() method. However, using the {patchwork} package, the spacing seems sensible. Like the marrangeGrob() method the space is too small to display all legends though.
library(ggplot2)
library(patchwork)
small.1<-ggplot(iris)+
geom_point(aes(x=Sepal.Length, y=Sepal.Width, color=Species, size=Petal.Width))
small.2<-ggplot(iris)+
geom_point(aes(x=Petal.Length, y=Petal.Width, color=Species, size=Petal.Length))
big<-ggplot(iris)+
geom_boxplot(aes(x=Species, y=Sepal.Length*Petal.Length, fill=Species))
((small.1 / small.2) | big) + plot_layout(guides = "collect") &
theme(legend.position = "bottom")

Created on 2022-02-09 by the reprex package (v2.0.1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | teunbrand |
