This is my dataset example:
df <- data.frame(group = rep(c("group1","group2","group3", "group4", "group5", "group6"), each=3),
X = paste(letters[1:18]),
Y = c(1:18))
As you can see, there are three variables, two of them categorical (group
and X
). I have constructed a line chart using ggplot2 where the X axis is X
and Y axis is Y
.
I want to shade the background using the group
variable, so that 6 different colors must appear.
I tried this code:
ggplot(df, aes(x = X, y = Y)) +
geom_rect(xmin = 0, xmax = 3, ymin = -0.5, ymax = Inf,
fill = 'blue', alpha = 0.05) +
geom_point(size = 2.5)
But geom_rect()
only colorize the area between 0
and 3
, in the X axis.
I guess I can do it manually by replicating the the geom_rect()
so many times as groups I have. But I am sure there must be a more beautiful code using the variable itself. Any idea?