Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using geom_rect with facets

Tags:

r

ggplot2

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?

like image 428
erc Avatar asked Feb 05 '23 00:02

erc


1 Answers

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)
like image 123
MrFlick Avatar answered Feb 08 '23 14:02

MrFlick