b00tsy
b00tsy

Reputation: 635

How to set background color of ggplot and facet_grid in R?

I have a rather complicated faceted boxplot in which I would like to make two groups more distinguishable, e.g. by coloring the background of the facets, but grouping 2 facet_grids would be possible, too, or adding a border around the 2 areas.

I tried to modify the background color for certain grids in a facet_grid based on the factor of a variable:

mtcars$type <- "Small"
mtcars$type[mtcars$cyl >= 6] <- "Medium"
mtcars$type[mtcars$cyl >= 8] <- "Big"
mtcars$type <- factor(mtcars$type)

mtcars$typeColor <- "black"
mtcars$typeColor[mtcars$cyl >= 8] <- "white"
mtcars$typeColor <- factor(mtcars$typeColor)

p <- ggplot(mtcars, aes(factor(gear), mpg, fill=factor(gear)))
p <- p + geom_boxplot()
p <- p + facet_grid(. ~ type)
p <- p + geom_rect(aes(xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, fill=factor(typeColor)))
show(p)

but I can't manage to plot a geom_rect into the background properly (fill of boxplot and fill of geom_rect are disturbing each other), and don't know about other solutions, yet.

Upvotes: 1

Views: 3012

Answers (1)

b00tsy
b00tsy

Reputation: 635

ok I've got it, tough one, cause the order is important:

p <- ggplot(mtcars, aes(factor(gear), mpg, fill=factor(gear)))
p <- p + scale_x_discrete()
p <- p + geom_rect(aes(xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, fill=(typeColor)))
p <- p + geom_boxplot()
p <- p + facet_grid(. ~ type)
p <- p + scale_fill_manual( values = c("black" = "black","white" = "white","3" = "green","4" = "red","5" = "blue"))
show(p)

Upvotes: 1

Related Questions