This is a follow up to this question: ggplot geom_rect() error “object not found”
I was answering this question that I noticed a strange behavior of alpha
in geom_rect()
. It seems when you pass the data from ggplot()
to geom_rect()
, it affects the "effctiveness" of alpha
, which leads to the color be less transparent. Look at the output of the two plotting options from the two answers provided to the aforementioned question for clarification.
library(tidyverse)
df <- tibble(Month = factor(c("2019-01", "2019-02", "2019-03")),
Value = c(4, 9, 7))
joran <- ggplot(df, aes(Month, Value, group = 1)) +
geom_line() +
theme_minimal() +
geom_rect(data =
data.frame(xmin = min(as.integer(df$Month)) - 0.5,
xmax = max(as.integer(df$Month)) + 0.5,
ymin = min(df$Value),
ymax = max(df$Value)),
aes(x = NULL,y = NULL,xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax),
alpha = 0.2, fill = "green")
M_M <- ggplot(df, aes(Month, Value, group = 1)) +
geom_line() +
theme_minimal() +
geom_rect(aes(xmin = min(as.integer(Month)) - 0.5,
xmax = max(as.integer(Month)) + 0.5,
ymin = min(Value),
ymax = max(Value)),
alpha = 0.2, fill = "green")
I can replicate Joran's plot by using alpha=0.1
. Just to be clear, I just plotted these on my machine, and these are not the same screenshots from that question.
I wonder what causes this behavior.
Joran's Plot:![]()
My Plot:![]()