对面使用geom_rect

bee*_*oot 3 r ggplot2

我想facet_grid用不平衡的观测值绘制一个用于构面的变量组合的,例如

dat <- data.frame(x = 1:6, 
                  y = 0:5, 
                  group = rep(c("A", "B"), each = 3),
                  var = rep(c("a", "a", "b"), times = 2))

> dat
  group var x y
1     A   a 1 0
2     A   a 2 1
3     A   b 3 2
4     B   a 4 3
5     B   a 5 4
6     B   b 6 5
Run Code Online (Sandbox Code Playgroud)

..并geom_rect在每个方面都添加相同的。

ggplot(dat) +
  geom_rect(xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = 3, fill = "red", alpha = .3) +
  geom_point(aes(x = x, y = y)) +
  facet_grid(group~var)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

但是geom_rect,即使我根本不使用aes(),似乎也有几个s相互重叠绘制。我该如何防止它们在各个方面看起来都一样?

MrF*_*ick 5

由于您并没有真正使用数据来绘制矩形,因此您应该使用annotate更高版本,以便它与数据或构面无关。例如

ggplot(dat) +
  annotate("rect", xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = 3, fill = "red", alpha = .3) +
  geom_point(aes(x = x, y = y)) +
  facet_grid(group~var)
Run Code Online (Sandbox Code Playgroud)