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
opened 10:23PM - 04 Apr 17 UTC
closed 08:01PM - 30 Oct 17 UTC
feature
themes
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")))
```
Apparently this script worked very well in the previous versions
library(tidyverse)
library(grid)
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
}
grid.draw(g)
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.
Thanks
Using a link from old development code can be outdated.
Just look at the current documentation:
Modify components of a theme — theme • ggplot2 (tidyverse.org)
strip.background
controls what you want.
system
Closed
July 18, 2021, 11:24pm
3
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.