8

I want to somehow indicate that certain rows in a multipanel figure should be compared together. For example, I want to make this plot:

enter image description here

Look like this plot (with boxes around panels made with PowerPoint):

enter image description here

Here's the code I made to use the first plot. I used ggplot and cowplot:

require(cowplot)
theme_set(theme_cowplot(font_size=12)) # reduce default font size
plot.mpg <- ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) + 
  geom_point(size=2.5)
plot.diamonds <- ggplot(diamonds, aes(clarity, fill = cut)) + geom_bar() +
  theme(axis.text.x = element_text(angle=70, vjust=0.5))
plot.mpg2 <- ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) + 
  geom_point(size=2.5)
plot.diamonds2 <- ggplot(diamonds, aes(clarity, fill = cut)) + geom_bar() +
  theme(axis.text.x = element_text(angle=70, vjust=0.5))
plot_grid(plot.mpg, plot.diamonds,plot.mpg2, plot.diamonds2, nrow=2,labels = c('A', 'B','C','D'))

Is there a change I can make to this code to get the borders that I want? Or maybe can I even make the panels A and B have a slightly different color than the background for panels C and D? That might be even better.

Tung
  • 26,371
  • 7
  • 91
  • 115
user2917781
  • 273
  • 2
  • 10
  • Perhaps related to https://stackoverflow.com/q/36963349/3358272 – r2evans Sep 05 '18 at 01:29
  • Seems relevant but I'm still not sure how to only put a border around certain rows in the multi-panel plot. The post seems relevant for putting a border around the entire plot. – user2917781 Sep 05 '18 at 03:07
  • Yeah, that's why I suggested "related", not certainly a duplicate. Sorry, I don't have much more than that, but my guess is that you'll need to get into the grobs and stuff, nothing `ggplot2`-native. – r2evans Sep 05 '18 at 03:09
  • This answer worked better than the one above in my case: https://stackoverflow.com/questions/58429757/draw-box-around-a-grid-of-plots-in-r – Vicky Ruiz Dec 15 '22 at 17:25

1 Answers1

14

Since the result of plot_grid() is a ggplot object, one way to do this is to use nested plot grids: one plot_grid() for each row, with the appropriate border added via theme().

plot_grid(
  # row 1
  plot_grid(plot.mpg, plot.diamonds, nrow = 1, labels = c('A', 'B')) +
    theme(plot.background = element_rect(color = "black")),

  # row 2
  plot_grid(plot.mpg2, plot.diamonds2, nrow = 1, labels = c('C', 'D')) +
    theme(plot.background = element_rect(color = "black")), 

  nrow = 2)

plot

Z.Lin
  • 28,055
  • 6
  • 54
  • 94