I want to create a boxplot using ggplot library in R.
What I want is that set various background color to each x value such as a following image. I cannot find any option for changing bgcolor of each x axis. Only thing I found is for changing entire background color such as 'theme_bw()' option
On first, fourth, fifth x axis, bgcolor is blue. However, there is no value on second, third, sixth x axis, so I want to set red color as bgcolor.
Thanks for your time!
Maybe you can build up something on this toy example:
nFac <- 6; nDat <- 10
df <- data.frame(x = gl(nFac, nDat),
y = runif(nFac * nDat))
rec <- data.frame(xmin = head(seq <- seq(0.5, nFac + .5, 1), -1),
xmax = tail(seq, -1),
alpha = c(.5, 0, 0, .5, .5, 0))
library(ggplot2)
ggplot() +
scale_x_discrete(seq_len(nFac)) +
geom_rect(data = rec,
aes(xmin = xmin,
xmax = xmax,
alpha = alpha),
ymin = -Inf,
ymax = Inf,
fill = "lightblue",
colour = "blue",
size = 2) +
geom_boxplot(data = df,
aes(x = x, y = y)) +
theme(panel.background = element_rect(fill = "pink"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank()) +
guides(alpha = FALSE)