[英]Add a coloured border between facets in ggplot2
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
. 我发现了这个问题,虽然我的数据是按照上面的例子,只有一行而不是
facet_grid
。
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; (我认为接受的答案不是最好的。它为每个绘图板和每个条带添加了彩色边框。)
facet_wrap
面板之间的列数与facet_grid
面板之间的列数不同; hence a slight adjustment for the facet_wrap
plot. 因此对
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.