4
votes

I'd like to plot a facet_grid with unbalanced observations for the combinations of variables used for facetting, e.g.

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

.. and add a geom_rect which should be the same in each facet.

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)

enter image description here

But it seems as if several geom_rects are plotted on top of each other, even though I am not using aes() at all. How can I prevent that so that they look the same in each facet?

2

2 Answers

6
votes

Since you're not really using data to plot the rects, you should use an annotate later so it's not tied to the data or facets. For example

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)
2
votes

Alternatively, supply data to the geom_rect layer:

ggplot(dat) +
  geom_rect(aes_all(vars = c('xmin', 'xmax', 'ymin', 'ymax')), fill = "red", alpha = .3,
            data.frame(xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = 3)) +
  geom_point(aes(x = x, y = y)) +
  facet_grid(group~var)

enter image description here