Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Request: multiple colours for facet strip.background #2096

Open
alexconingham opened this Issue Apr 4, 2017 · 2 comments

Comments

Projects
None yet
4 participants

This code generates the plot, and changes the strip backgrounds to red:

p <- ggplot(mpg, aes(displ, cty)) + geom_point() + facet_grid(. ~ cyl) +
theme(strip.background = element_rect(fill="red"))

It would be useful to be able to have each strip a different colour, something like the below seemed intuitive though just makes them red (first colour in the call is used)

p <- ggplot(mpg, aes(displ, cty)) + geom_point() + facet_grid(. ~ cyl) +
theme(strip.background = element_rect(fill=c("red","green","blue","yellow")))

Contributor

stefanedwards commented Apr 10, 2017

AFAIK it is entirely doable, but introducing vectorized theme elements as you propose raises the question of what users will expect when they are applied to other aspects.

In the meanwhile, here is a solution that modifies the resulting grob. The plot is one of the first examples from facet_grid.

p <- ggplot(mpg, aes(displ, cty)) + geom_point() + facet_grid(drv ~ cyl)

image

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
}
grid.draw(g)

image

Might be pretty with some other colour choices...

Sorry, I'm not particularly great in R, but would it be possible to map the fill of the facet strip background to the variable that is being used for the facet (or some other variable)?

Something like...
... + facet_grid(. ~ cyl, aes(fill=cyl))

I know it may seem a bit redundant to also colour by the facetting variable but there are cases where it can add some clarity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment