Home > Mobile >  ggplot2 and grid.arrange, place legend below arranged plots
ggplot2 and grid.arrange, place legend below arranged plots

Time:02-05

I am facing a problem when I arrange 2 ggplots next to each other using grid.arrange(). I want to place a legend evenly below both plots.

So I have (pseudocode):

 p1 <- ggplot(data = df, aes(group = name, color=as.factor(fac), y = ys, x= (xs)))  
    geom_point()  
    geom_line()  
    theme(legend.position="bottom")

 p2 <- ggplot(data = df, aes(group = name, color=as.factor(fac), y = ys, x= (xs)))  
    geom_point()  
    geom_line()  

  grid.arrange(p1,p2, ncol=2, widths=c(0.9,1))

Is there any possibility to arrange the legend so that it is positioned evenly below both plots? If I do it as above, the legend is (logically) placed below the first plot.

CodePudding user response:

With package patchwork you could try this...

library(ggplot2)
library(patchwork)

p1 <- ggplot(data = mtcars, aes(group = gear, color=as.factor(am), y = mpg, x = hp))  
  geom_point()  
  geom_line()

p2 <- ggplot(data = mtcars, aes(group = gear, color=as.factor(am), y = mpg, x = hp))  
  geom_point()  
  geom_line()

p1   p2  
  plot_layout(guides = "collect") &
  theme(legend.position='bottom')

Created on 2022-02-04 by the reprex package (v2.0.1)

  •  Tags:  
  • Related