beetroot beetroot -4 years ago 197
R Question

Using geom_rect with facets

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_rect
s 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?

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download