CCurtis
CCurtis

Reputation: 1932

Adjust margins of grob object in r

I made a grob object using the cowplot package. I'm adding grid.lines() and grid.text() objects to finished grob but as it comes out of cowplot it fills the whole page. How can I adjust the margins of the grob object to add some white space around the edges? Example code below.

library(ggplot2)
library(cowplot)

p1 <- ggplot(mtcars, aes(disp, mpg)) + 
  geom_point()
p2 <- ggplot(mtcars, aes(qsec, mpg)) +
  geom_point()
p3 <- ggplot(mtcars, aes(disp, mpg)) + 
  geom_point()
p4 <- ggplot(mtcars, aes(qsec, mpg)) +
  geom_point()
plot_grid(p1, p2, p3, p4, ncol = 2 ,nrow = 2,align="hv")

Upvotes: 1

Views: 951

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174468

You just use theme(plot.margin = ...) as you would in a ggplot:

library(ggplot2)
library(cowplot)

p1 <- ggplot(mtcars, aes(disp, mpg)) + 
  geom_point()
p2 <- ggplot(mtcars, aes(qsec, mpg)) +
  geom_point()
p3 <- ggplot(mtcars, aes(disp, mpg)) + 
  geom_point()
p4 <- ggplot(mtcars, aes(qsec, mpg)) +
  geom_point()
plot_grid(p1, p2, p3, p4, ncol = 2 ,nrow = 2,align="hv")


plot_grid(p1, p2, p3, p4, ncol = 2 ,nrow = 2,align="hv") + 
  theme(plot.margin = unit(c(20,20,20,20), "points"))

Created on 2020-04-29 by the reprex package (v0.3.0)

Upvotes: 3

Related Questions