Home > front end >  ggplot - how to put title in a box if I am already using facets for something else?
ggplot - how to put title in a box if I am already using facets for something else?

Time:11-13

I found some other answers here on the site, but they all seem to exploit the fact that using facets creates a box with a "title" which you then can manipulate.

However, this doesn't work if I am already using facets for something else.

library(ggplot)
library(gridExtra)

mtcars %>% 
  split(.$am) %>% 
  map(~ggplot(., aes(x = mpg, y = cyl))  
        geom_point()  
        facet_grid(rows = vars(vs),
                   cols = vars(carb))  
        ggtitle(.$am)) %>% 
  grid.arrange(grobs = .)

How can I put the plot title in the above example in a white rectangle with black border?

CodePudding user response:

You can use element_markdown from the ggtext package:

library(ggplot)
library(gridExtra)
library(ggtext)

mtcars %>% 
  split(.$am) %>% 
  map(~ggplot(., aes(x = mpg, y = cyl))  
        geom_point()  
        facet_grid(rows = vars(vs),
                   cols = vars(carb))  
        ggtitle(.$am)  
        theme(plot.title = element_markdown(box.color = "black", 
                                            linewidth = 0.5,
                                            r = unit(0, "mm"), linetype = 1,
                                            padding = unit(3, "mm")))) %>% 
        grid.arrange(grobs = .)

enter image description here

  • Related