Fael
Fael

Reputation: 183

How to get more than one background color on ggplot2 plot area?

Is it possible to have more than one background color for the plot area (but not the panel area) on a ggplot2 graph? A hunch tells me that it might be possible to do that as some sort of background color for axes.

This is what my current chart looks like:

And this is what I would like to achieve:

[The final colours will certainly be different. I just used this example in its simplest form in order to ease the discussion]

I tried passing "fill" arguments to:

theme(axis.text.y = element_text(fill = "red"),

but it obviously failed as that argument is meant for element_rect.

Upvotes: 8

Views: 638

Answers (1)

user20650
user20650

Reputation: 25914

You can add grobs in the margins - i had to mess about with the annotation ranges to get it to fit - so expect there is a more robust method. Adapted from this question: How to place grobs with annotation_custom() at precise areas of the plot region?

library(grid)

data(mtcars)
#summary(mtcars)

myGrob <- grobTree(rectGrob(gp=gpar(fill="red", alpha=0.5)),
               gTree(x0=0, x1=1, y0=0, y1=1, default.units="npc"))

myGrob2 <- grobTree(rectGrob(gp=gpar(fill="yellow", alpha=0.5)),
               gTree(x0=0, x1=1, y0=0, y1=1, default.units="npc"))

p <- ggplot(mtcars , aes(wt , mpg)) + 
 geom_line() +
 scale_y_continuous(expand=c(0,0)) + 
 scale_x_continuous(expand=c(0,0)) + 
 theme(plot.margin=unit(c(1, 1, 1,1), "cm")) +
 annotation_custom(myGrob, xmin=-0.5, xmax=1.5, ymin=7.4, ymax=33.9 ) +
 annotation_custom(myGrob2, xmin=1.5, xmax=5.4, ymin=7.4, ymax=10.4 )

g <- ggplotGrob(p)
g$layout$clip[g$layout$name=="panel"] <- "off"
grid.draw(g)

enter image description here

Upvotes: 7

Related Questions