0

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()

Graph

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.

nicholas
  • 903
  • 2
  • 12
  • 1
    With this setup, each facet has 13 or 25 observations with value min/max, each of which will trigger an overlapping geom_rect, which will quickly make them look less transparent than you expect. – Jon Spring Mar 14 '23 at 04:08
  • Relevant: https://stackoverflow.com/questions/57394946/control-alpha-blending-opacity-of-n-overlapping-areas/57446700#57446700 – Jon Spring Mar 14 '23 at 04:09
  • I misstated that, annotate won't work well here, as it will put the same annotations on each facet. – Jon Spring Mar 14 '23 at 04:18

1 Answers1

1
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()

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53