2017-03-17 31 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