1

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.

b00tsy
  • 635
  • 8
  • 25
  • 1
    the geom_rect layer should probably go first – baptiste Oct 17 '13 at 11:06
  • I tried that on the mtcars data which resulted in this error: `Discrete value supplied to continuous scale`, however it works on the data I'm actually plotting, but gives still strange results when I use it as a colour (two legends, and fill of boxplots / facets_grids get mixed) – b00tsy Oct 17 '13 at 11:20
  • possible duplicate of [Conditionally change panel background with facet\_grid?](http://stackoverflow.com/questions/9847559/conditionally-change-panel-background-with-facet-grid) – juba Oct 17 '13 at 12:25
  • similar, but I think what gives me the hard time is that somehow the fill of the boxplot and the fill of the facet background is disturbing each other, maybe it's not possible at all at the moment – b00tsy Oct 17 '13 at 12:45
  • ok after some more fiddling this does the trick: `p <- p + scale_x_discrete()` (right after ggplot, then geom_rect), but know I'm trying to set the color manually, without success, yet. Any hints? – b00tsy Oct 17 '13 at 13:44

1 Answers1

1

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)
b00tsy
  • 635
  • 8
  • 25
  • The order shouldn't be important if you're using a named vector of colours, at least in newish versions of ggplot2. – naught101 Jul 18 '14 at 05:19