为什么 geom_rect 看起来各不相同?

Why geom_rect looking different across facets?

我正在尝试为同样被分面的情节的不同象限着色。我注意到 geom_rect 参数的颜色在不同方面看起来不同。我希望这是一个例子:

# Load tidyverse
library(tidyverse)

# Make some fake data
set.seed(5)
dat <- tibble(
  y = rnorm(10, 0, 1),
  ub = y + .2,
  lb = y - .2,
  x = sample(1:7, size=10, replace=TRUE),
  z = sample(c("one", "two", "three"), size=10, replace=TRUE),
)

# Plot
dat %>% 
  ggplot(aes(x = x, y = y)) +
  geom_rect(data=NULL, aes(xmin=4, xmax=Inf, ymin=0, ymax=-Inf), fill="yellow", color = "white", alpha = .05) +
  geom_rect(data=NULL, aes(xmin=-Inf, xmax=4, ymin=Inf, ymax=0), fill="yellow", color = "white", alpha = .05) +
  geom_rect(data=NULL, aes(xmin=-Inf, xmax=4, ymin=-Inf, ymax=0), fill="red", color = "white", alpha = .05) +
  geom_rect(data=NULL, aes(xmin=4, xmax=Inf, ymin=0, ymax=Inf), fill="springgreen", color = "white", alpha = .05) +
  geom_point(position= position_dodge2(width = .6)) +
  geom_errorbar(aes(ymin = lb, ymax = ub, width = .6), position= position_dodge2(width = .6, preserve = "single")) +
  facet_grid(~ z) +
  theme_classic()

任何人都可以向我解释为什么 geom_rect 框在某些方面比其他方面更亮吗?我该如何解决这个问题?

这里发生的事情是 geom_rect 每次调用时都会将矩形叠加在一起。如果对面进行排序,您会发现第二个不如第一个透明,第三个不如第二个透明。

解决办法是用annotate代替geom_rect:

dat %>% 
  mutate(z = factor(z, levels = c("one", "two", "three"))) %>% 
  ggplot(aes(x = x, y = y)) +
  annotate("rect", xmin=4, xmax=Inf, ymin=0, ymax=-Inf, fill="yellow", color = "white", alpha = .05) +
  annotate("rect", xmin=-Inf, xmax=4, ymin=Inf, ymax=0, fill="yellow", color = "white", alpha = .05) +
  annotate("rect", xmin=-Inf, xmax=4, ymin=-Inf, ymax=0, fill="red", color = "white", alpha = .05) +
  annotate("rect", xmin=4, xmax=Inf, ymin=0, ymax=Inf, fill="springgreen", color = "white", alpha = .05) +
  geom_point(position= position_dodge2(width = .6)) +
  geom_errorbar(aes(ymin = lb, ymax = ub, width = .6), position= position_dodge2(width = .6, preserve = "single")) +
  facet_grid(~ z) +
  theme_classic()

结果: