在ggplot2中为分面之间添加有色边框

3

我希望在每个图形之间添加一条厚重的深灰色条。我不想在每个图形周围加边框,而是在图形之间添加一条深灰色条。

library(ggplot2)

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

尽管我的数据如上面的例子一样,只有一行而不是facet_grid,但我找到了这个问题。


没有相应的主题元素,所以需要使用 grid/gridExtra 进行修改。 - alistaire
1个回答

6
这是基于您提供的问题的未被接受的答案。(我认为被接受的答案并不是最好的。它会在每个绘图面板和条带周围添加彩色边框。) 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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接