Home > Enterprise >  How to keep ggplot from repeating some elements multiple times in each facet
How to keep ggplot from repeating some elements multiple times in each facet

Time:07-01

How can I prevent ggplot from repeating all geoms multiple times in each facet?

Imagine I want to create a plot that shows the temperature along the x-axis across multiple facets. For added effect, I create two geom_rects() that show if the temperature is above or below freezing.

In group "A" geom_rect is drawn once. In group "B" geom_rect is drawn twice. In group "C" geom_rect is drawn three times.

Because geom_rect is repeated different times the alpha value of the facets becomes different (please note the difference from top to bottom).

How can I avoid this?

library(tidyverse)

set.seed(1)
df <- tibble(
  facet_var = c("A", "B", "B", "C", "C", "C"),
  celcius = rnorm(n = 6),
  y = as.factor(c(1, 1, 2, 1, 2, 3)))


df %>% 
  ggplot(aes(x = celcius, y = y)) 
  geom_point() 
  geom_rect(xmin = -2.5, xmax=0.0, 
            ymax=3.5 , ymin=0, 
            fill = "blue",  alpha =0.2) 
  geom_rect(xmin = 0, xmax=2,
            ymax=3.5, ymin=0, 
            fill = "red",  alpha =0.2) 
  facet_grid(rows = vars(facet_var), scales = "free_y", space = "free_y")

Created on 2022-06-30 by the reprex package (v2.0.1)

CodePudding user response:

You could use annotate with geom rect:

(Set ymin to -Inf and ymax to Inf to retain the "free_y" spacing.)

library(tidyverse)

set.seed(1)

df <- tibble(
  facet_var = c("A", "B", "B", "C", "C", "C"),
  celcius = rnorm(n = 6),
  y = as.factor(c(1, 1, 2, 1, 2, 3)))

df %>%
  ggplot(aes(celcius, y))  
  geom_point()  
  annotate("rect", xmin = -2.5, xmax = 0.0, ymin = -Inf, ymax = Inf, fill = "blue", alpha = 0.2)  
  annotate("rect", xmin = 0, xmax = 2, ymin = -Inf, ymax = Inf, fill = "red", alpha = 0.2)  
  facet_grid(rows = vars(facet_var), scales = "free_y", space = "free_y")

Created on 2022-06-30 by the reprex package (v2.0.1)

  • Related