首页 > 解决方案 > 在ggplot中结合geom_rect和facet_grid的麻烦

问题描述

我想在一个简单的情节的每个方面对部分背景进行着色。如果我省略 faceting 并运行 geom_rect + geom_point,预期的结果将如下面的 MRE 所示。如果我省略矩形并运行 geom_point + facet_grid,则预期的 4 个面板的每个点都在正确的方面。但是当我结合 geom_rect + geom_point + 和 facet_grid 时,第一类中的点,只有那些点被绘制在每个方面。请问这是怎么回事???

library(ggplot2)
set.seed(42)
syn.dat <- data.frame(
   category.1 = as.factor(rep(c("1A", "1B"), each = 8)),
   category.2 = as.factor(rep(rep(c("2A", "2B"), times = 2), each = 4)),
   x = rep(-1:2, each = 4) + runif(8, max = .4),
   y = rep(-1:2, each = 4) + runif(8, max = .4))

ggplot() +
   geom_rect(aes(xmin = -Inf, xmax = Inf, ymin = .5, 
      ymax = Inf), fill = "lightyellow") +
   geom_point(data = syn.dat, aes(x = x, y = y)) +
   facet_grid(cols = vars(category.1), 
      rows = vars(category.2))

无刻面工作

无矩形工作

两者都失败

标签: rggplot2

解决方案


我对此并不完全确定,但可能是您需要明确地向自身提供data参数,以便正确获取所有值?ggplotfacet_grid

ggplot(syn.dat) +
    geom_rect(aes(xmin = -Inf, xmax = Inf, ymin = 0.5, ymax = Inf), fill = "lightyellow") +
    geom_point(aes(x = x, y = y)) +
    facet_grid(rows = vars(category.2), vars(cols = category.1))

在此处输入图像描述


推荐阅读