Create border and title for each column in `facet_

2020-07-18 06:26发布

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

enter image description here

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)

1条回答
家丑人穷心不美
2楼-- · 2020-07-18 06:43

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)

enter image description here

查看更多
登录 后发表回答