Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Control alpha on geom_rect with facet_wrap

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading