2017-03-17 14 views
1

各ファセットの間に太い濃いグレーのバーを追加したいと思います。私は、各ファセットの周りに境界線が必要ではなく、プロットの間に濃いグレーのバーがあります。ggplot2のファセット間に色付きの枠を追加

library(ggplot2) 

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

私のデータは、上記の例のようにのみ1行ないfacet_gridであるが、私はthis質問を発見しました。

+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

関連する問題