Create border and title for each column in `facet_wrap`

给你一囗甜甜゛ 提交于 2020-05-11 16:07:24

问题


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)

回答1:


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)



来源:https://stackoverflow.com/questions/59126171/create-border-and-title-for-each-column-in-facet-wrap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!