Alpha parameter doesn’t work on geom_rect!!! Sort of…

The parameter alpha in the R package ggplot2 is used to express the transparency of the fill colour of the function geom_

However for the function geom_rect it might not work as aspected.

In my latest work, I tried to combine different geom function but I was stuck when all was covered when I used geom_rect.
Let’s see an example:

library("dplyr")
library("ggplot2")
df = 
  data.frame(
    x = c(rep(1, 25), rep(2, 25), rep(3, 25)),
    y = c(sample(1:50, 25), sample(51:100, 25), sample(101:150, 25)),
    classes = c(rep("A", 25), rep("B", 25), rep("C", 25)))

head(df)
#  x  y classes
#1 1 45       A
#2 1  4       A
#3 1 41       A
#4 1 32       A
#5 1  8       A
36 1 14       A

If we plot the data using geom_jitter and geom_boxplot we obtain the plot:

ggplot(data = df,
       aes(x = x, y = y, colour = classes)) + 
  geom_jitter() +
  geom_boxplot(alpha = 0.2) +
  theme_minimal()

Now, if we can introduce the coordinates for geom_rect with the following

df =
  df %>% 
  group_by(classes) %>% 
  mutate(ymin = min(y), ymax = max(y))
#      x     y classes  ymin  ymax
# <db> <int> <fct>   <dbl> <dbl>
#1     1    45 A           4    50
#2     1     4 A           4    50
#3     1    41 A           4    50
#4     1    32 A           4    50
#5     1     8 A           4    50
#6     1    14 A           4    50

But if we add geom_rect the results are not what we want.

ggplot(data = df,
       aes(x = x, y = y, colour = classes)) + 
  geom_jitter() +
  geom_boxplot(alpha = 0.2) +
  geom_rect(aes(xmin = x - 0.5, 
                xmax = x + 0.5,
                ymin = ymin,
                ymax = ymax,
                fill = classes), 
    alpha = 0.1) +
  theme_minimal()

The alpha parameter seem not to work.

This is due to the fact that geom_rect adds as many shapes as the number of entries.

This nullifies the parameter alpha.

Therefore, in order to produce our ideal plot we have to reduce the entries of the dataset:

df2 = 
  df %>% 
  select(classes, x, ymin, ymax) %>% 
  distinct()

print(df2)
## A tibble: 3 x 4
## Groups:   classes [3]
#  classes     x  ymin  ymax

#1 A           1     1    50
#2 B           2    54    94
#3 C           3   101   148

And to rewrite the plot function:

ggplot() + 
  geom_jitter(data = df,
              aes(x=x, y=y, colour=classes)) +
  geom_boxplot(data = df,
               aes(x=x, y=y, colour=classes),
               alpha=0.2) + 
  geom_rect(data = df2, 
            aes(xmin = x - 0.5, 
                xmax = x + 0.5,
                ymin = ymin,
                ymax = ymax,
                fill = classes), 
            alpha=0.1) +
  theme_minimal()