2017-03-17 34 views
1

我希望在每个面之间添加一个深灰色条。我不想在每个方面都有边框,而是在情节之间有一个深灰色的条。在ggplot2的各个面之间添加彩色边框

library(ggplot2) 

ggplot(mpg, aes(cty, hwy, color = factor(year))) + 
    geom_point() + 
    facet_wrap(~ cyl, nrow = 1) 

我发现this问题,虽然我的数据是按照上面的例子中,只有一个排,而不是facet_grid

+0

这里没有一个主题元素这一点,所以它会涉及'grid' /'gridExtra'黑客。 – alistaire

回答

2

这是基于您未链接的问题的接受答案。 (我认为接受的答案并不是最好的,它在每个小区面板和每个小区上添加了一个彩色边框)。facet_wrap小组之间的列数与facet_grid小组之间的列数不同;因此对facet_wrap情节进行了微调。

library(ggplot2) 
library(grid) 
library(gtable) 

p = ggplot(mpg, aes(cty, hwy, color = factor(year))) + 
    geom_point() + 
    facet_wrap(~ cyl, nrow = 1) 

gt <- ggplotGrob(p) 


panels = subset(gt$layout, grepl("panel", gt$layout$name), t:r) 

# The span of the vertical gap 
Bmin = min(panels$t) - 1 
Bmax = max(panels$t) 

# The columns of the gaps (two to the right of the panels 
cols = unique(panels$r)[-length(unique(panels$r))] + 2 

# The grob - grey rectangle 
g = rectGrob(gp = gpar(col = NA, fill = "grey40")) 

## Add greyrectangles into the vertical gaps 
gt <- gtable_add_grob(gt, 
     rep(list(g), length(cols)), 
     t=Bmin, l=cols, b=Bmax) 

## Draw it 
grid.newpage() 
grid.draw(gt) 

enter image description here