I have been trying to collect legends of plots created in a loop. However, this fails to produce the desired result, as the legends are not collected. I tried
(res[[1]] / res[[2]]) + plot_layout(guides = "collect") + theme(legend.position = "bottom")
where res[[1]]
and res[[2]]
are list elements created in the loop.
Any advice would be much appreciated.
Remove + theme(legend.position = "bottom")
:
library(ggplot2)
library(patchwork)
p1 <- ggplot(data = mtcars, aes(x = disp, y = cyl, color = as.factor(vs))) +
geom_point()
p2 <- ggplot(data = mtcars, aes(x = disp, y = cyl, color = as.factor(vs))) +
geom_point()
p1 + p2 + plot_layout(guides = "collect")
Or if you'd like to place the legend in the center:
p1 + p2 + plot_layout(guides = "collect") & theme(legend.position = 'bottom')