Control alpha on geom_rect with facet_wrap

Advertisements

I am trying to get partially transparent rectangles on a faceted plot. The following illustrates what I’m trying to do, except that the alpha argument isn’t working:

library(dplyr)
library(ggplot2)

df <- iris %>% 
  filter(Species == "setosa" | Species == "versicolor") %>% 
  group_by(Species) %>% 
  mutate(plq = cut(Petal.Length,
                   quantile(Petal.Length, 
                            probs = seq(0, 1, 0.5)),
                   labels = seq(1:(length(seq(0, 1, 0.5)) - 1)), 
                   include.lowest = TRUE)) %>% 
  ungroup() %>% 
  group_by(Species, plq) %>% 
  mutate(max = max(Petal.Length), 
         min = min(Petal.Length)) %>% 
  ungroup() %>% 
  mutate(min = if_else(plq == 2, 
                       min, NA),
         max = if_else(plq == 2, 
                       max, NA))

df %>% 
  ggplot(aes(x = Petal.Length)) +
  stat_density(geom = "line", position = "identity", adjust = 3) +
  geom_rect(aes(xmin = min, xmax = max, ymin = -Inf, ymax = Inf), alpha = 0.2) +
  facet_wrap(vars(Species)) +
  theme_classic()

The plot is exactly what I want, except that the alpha argument isn’t working. I’ve found several other relevant Q&A’s (here and here), but I don’t think either one applies directly to my question.

>Solution :

library(dplyr) 
df_rect <- df %>%
  filter(!is.na(max)) %>%
  distinct(Species, max, min)

df %>% 
  ggplot(aes(x = Petal.Length)) +
  stat_density(geom = "line", position = "identity", adjust = 3) +
  geom_rect(aes(xmin = min, xmax = max, ymin = -Inf, ymax = Inf), 
            inherit.aes = FALSE, # or put Petal.Length only in the stat_density layer
            data = df_rect, alpha = 0.2) +
  facet_wrap(vars(Species)) +
  theme_classic()

Leave a ReplyCancel reply