必须将 geoms 乘以 facets 的数量?

Having to multiply geoms by number of facets?

我想在我的数据后面有多个矩形,但我也想使用多个面,每个面都会出现这些矩形。我首先 运行 下面的代码得到了错误:Aesthetics must be either length 1 or the same as the data (12): fill

这是我的代码:

block_rects <- data.frame(xstart_rect=c(-0.5,  0.5,  1.5,  2.5,  3.5,  4.5),
                          xend_rect=c(0.5, 1.5, 2.5, 3.5, 4.5, 5.5))
df <- data.frame(xs=c(1,2,3),ys=c(1,2,3),cond=c("a","b","f"),fs=c("x","x","y"))
df %>% ggplot(aes(x=xs,y=ys,color=cond)) + 
  geom_rect(inherit.aes = FALSE,
            data = block_rects, aes(xmin = xstart_rect, xmax = xend_rect, 
                              ymin = -Inf, ymax = Inf), 
            fill = c("#f1f1f1", "white","white","white","#f1f1f1","white")) +
    geom_point() +
  facet_wrap(~ fs)

但是,我意识到当我 geom_rect 中的 fill 向量中的项目数加倍 时,它起作用了。我发现我必须将 fill 向量乘以绘图的面数(例如,如果我将 fs 更改为 c("x","y","z") 我需要乘以 fill 列三个)。

这种行为到底是怎么回事?这是代码中的错误吗?如果没有,我应该如何编写代码以便可以使用任意数量的方面?我不想在 geom_rect.

中显式编码哪些变量被分面

如您所想,您正在绘制 12 个矩形(每个面 6 个矩形)。因此 ggplot 需要整体填充颜色或为每个颜色标识的填充颜色。

比重复填充颜色更简单的解决方法是利用美学映射,将每个矩形的填充颜色放入矩形 data.frame。

block_rects <- data.frame(xstart_rect=c(-0.5,  0.5,  1.5,  2.5,  3.5,  4.5),
                     xend_rect=c(0.5, 1.5, 2.5, 3.5, 4.5, 5.5),
                     fill = c("#f1f1f1", "white","white","white","#f1f1f1","white"))

这允许您将 fill 映射到 geom_rectaes 中的变量。使用 scale_fill_identity 以便它使用给定的颜色名称。

ggplot(df, aes(x=xs,y=ys,color=cond)) + 
    geom_rect(inherit.aes = FALSE,
            data = block_rects, aes(xmin = xstart_rect, xmax = xend_rect, 
                                ymin = -Inf, ymax = Inf, fill = fill)) +
    geom_point() +
    facet_wrap(~ fs) +
    scale_fill_identity()