Jean_N
Jean_N

Reputation: 529

Putting different ggplots next to each other, while keeping a common facet wrap

Background: I have a set of ggplots (different types) that I would to have displayed next to each other, but they share a common facet.

Here is a minimal working example:

 p1 <- mtcars %>% ggplot(mapping = aes(x = wt, y = qsec)) + geom_point() +
  facet_wrap(~ cyl)

plot(p1)

p2 <- mtcars %>% ggplot(mapping = aes(x = disp, y = qsec)) + geom_smooth() +
  facet_wrap(~ cyl)

plot(p2)    

Question I would like to have the first plot of p1 (say, above) the first plot of p2, the second plot of p1 above the second plot of p2 and so on... How could I do that? So far my solution is to have p1 and p2 separately, but this is not what I am looking for. Any help would be appreciated.

Upvotes: 2

Views: 2153

Answers (2)

Ben G
Ben G

Reputation: 4348

You can also use the cowplot package available on cran.

library(tidyverse)
library(cowplot)

p1 <- mtcars %>% ggplot(mapping = aes(x = wt, y = qsec)) + geom_point() +
  facet_wrap(~ cyl)

p2 <- mtcars %>% ggplot(mapping = aes(x = disp, y = qsec)) + geom_smooth() +
  facet_wrap(~ cyl)

plot_grid(p1, p2, ncol = 1, align = "v")

enter image description here

I like cowplot a lot, but it does change the default theme of ggplot. If you want to change it back, you need to add this: theme_set(theme_gray()).

Upvotes: 3

markus
markus

Reputation: 26373

Try the patchwork package

# install.packages("devtools")
# devtools::install_github("thomasp85/patchwork")
library(patchwork)
p1 / p2

enter image description here

Upvotes: 4

Related Questions