Changing my facet labels to different colors (strip.background)

Currently, I'm using the latest version of R and I have found that this script widely used is outdated and doesn't work. This is the site

Apparently this script worked very well in the previous versions


p <- ggplot(mpg, aes(displ, cty)) + geom_point() + facet_grid(drv ~ cyl)
g <- ggplot_gtable(ggplot_build(p))
stripr <- which(grepl('strip-r', g$layout$name))
fills <- c("red","green","blue","yellow")
k <- 1
for (i in stripr) {
j <- which(grepl('rect', g$grobs[[i]]$grobs[[1]]$childrenOrder))
g$grobs[[i]]$grobs[[1]]$children[[j]]$gp$fill <- fills[k]
k <- k+1

This produces the following graph:

However, when I run it, I get the error

Error in *tmp* [[j]] : attempt to select less than one element in get1index

Thus, I would like to ask the community if you have found another method to change the colors of each rectangle of the label, since ggplot2 natively doesn't do it.


Using a link from old development code can be outdated.

Just look at the current documentation:
Modify components of a theme — theme • ggplot2 (
strip.background controls what you want.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.