Reputation: 1946
I wish to add a thick dark grey bar in between each facet. I don't want a border around each facet, instead a dark grey bar in between plots.
library(ggplot2)
ggplot(mpg, aes(cty, hwy, color = factor(year))) +
geom_point() +
facet_wrap(~ cyl, nrow = 1)
I found this question although my data is as per the example above, only one row and not a facet_grid
.
Upvotes: 3
Views: 1830
Reputation: 32789
This is based on the not-accepted answer to the question that you linked. (I think the accepted answer is not the best. It adds a coloured border round each of the plot panels and each of the strips.) The number of columns between facet_wrap
panels is different from the number of columns between facet_grid
panels; hence a slight adjustment for the facet_wrap
plot.
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)
Upvotes: 6