patchwork plot.background control

I am attempting to to control ggplot2 theme plot.background element.rect.
What I want:
On this case, I want a single dotted element.rect line around the background that contains all the patched plots.

What I have attempted:
Used the "&" to patch a theme element.rect which adds rect around all plots.

Here is the reprex:

library(ggplot2)
library(patchwork)

g1 <- ggplot(mtcars, aes(wt, mpg)) + 
        theme_void() + 
        theme(panel.background = element_rect(fill ="gray76", color  = 'red', size = 1),
              plot.background = element_rect(color  = NA, size = 4)) 

g2 <- ggplot(mtcars, aes(wt, mpg)) + 
        theme_void() + 
        theme(panel.background = element_rect(fill ="gray76", color  = 'red', size = 1),
              plot.background = element_rect(color  = "brown", size = 4))


g3<- ggplot(mtcars, aes(wt, mpg)) + 
        theme_void() + 
        theme(panel.background = element_rect(fill ="gray76", color  = 'red', size = 1)) 

g1 + g2 + g3 +
   plot_layout(nrow = 1, widths = c(1, 2, 1)) &
   theme(plot.margin = unit(c(.2,.2,.2,.2), "cm")) &
   theme(plot.background = element_rect(color  = 'blue', size = 2,linetype = 'dotted', fill ="ivory"))

Here is the rendered plot:

You need to put the patchwork theme in a plot_annotation() wrapper.

g1 + g2 + g3 +
  plot_layout(nrow = 1, widths = c(1, 2, 1)) &
  theme(plot.margin = unit(c(.2,.2,.2,.2), "cm")) &
  plot_annotation(theme = theme(plot.background = element_rect(color  = 'blue', size = 2,linetype = 'dotted', fill ="ivory")))

rcommunity

2 Likes

That is it! Thanks @elmstedt

Happy to help.

Good luck and stay safe!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.