为facet_wrap中的每一列创建边框和标题 [英] Create border and title for each column in `facet_wrap`

查看:267
本文介绍了为facet_wrap中的每一列创建边框和标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在facet_wrap的每个方面周围放置带有标签和标题的黑色边框. 与此类似:

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

样本数据:

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)

推荐答案

您可以通过手动添加到ggplot gtable中来做到这一点:

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)

这篇关于为facet_wrap中的每一列创建边框和标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆