简体   繁体   中英

Create border and title for each column in `facet_wrap`

I want to put black borders with labels and titles around each facet in facet_wrap . Something similar to this:

在此处输入图像描述

Sample data:

library(tidyverse)

mtcars %>% 
  mutate(gear = factor(gear, levels = c(4, 3, 5))) %>%
  ggplot(aes(mpg, disp)) + 
  geom_point() + 
  geom_smooth(method = "lm") + 
  facet_wrap(~am + gear)

You can do this by manually adding to the ggplot gtable :

library(tidyverse)    
library(grid)
library(gtable)

p <- mtcars %>% 
  mutate(gear = factor(gear, levels = c(4, 3, 5))) %>%
  ggplot(aes(mpg, disp)) + 
  geom_point() + 
  geom_smooth(method = "lm") + 
  facet_wrap(~am + gear)

g <- ggplotGrob(p)

# add basic black rectangle round the columns
gt <- gtable_add_grob(g, 
                     gList(
                      rectGrob(gp = gpar(col = "black", lwd=3, fill=NA)), 
                      rectGrob(gp = gpar(col = "black", lwd=3, fill=NA))),
                     t=7, b=13, l=c(5, 9))
# look
# grid.newpage(); grid.draw(gt)

# add title above columns
tit1 <-  textGrob("title1", x=0, hjust=0) ; tit2 =  textGrob("title2", x=0, hjust=0) 
gt <- gtable_add_rows(gt, grobHeight(tit1) + unit(0.5, "line"), 0)
gt <- gtable_add_grob(gt, gList(tit1, tit2), t=1, l=c(5, 9))
# draw
grid.newpage(); grid.draw(gt)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM