简体   繁体   中英

ggplot2 facet_grid() strip_text_x() different colours based on factor

Is there a way to colour the names or strip backgrounds (not the backgrounds of the actual grids, as has been answered in this post: Conditionally change panel background with facet_grid? ) of the facets in ggplot2's facet_grid?

In the following example:

#create simple dataframe for plotting
xy <- data.frame(x = rep(1:10, times=3), y = rep(10:1, times=3), type = rep(LETTERS[1:2], each=5), type2 = rep(LETTERS[3:5], each=10), category = rep(c("control", "exp", "control"), each=10))
xy
#create base plot
plot <- ggplot(data = xy)+
geom_point(aes(x = x, y = y))+
facet_grid(type ~ type2)

#plot base plot   
plot

Is there a way to colour the text or the background of theme(strip.text.x = element_text(size = 11, face="bold")) (?strip.background.x?) depending upon a categorical variable (for example, "category" in the data frame I have specified above, so all the controls have a red strip, all of the exp - a green one)?

Thanks in advance!

PS What I'm actually trying to do is present the results of a biological experiment:

  • two boxplots for every gene to show the variability; gene name is in the strip

  • the background of the grid is either white or grey, with grey showing genes which are controls

  • I'd like to use the colour of the text in the header to denote whether the gene is significant or not in my experiment (I need to show both the validated and non-validated genes in the same plot)

@Roland taught me to hack around with the grid graphics objects on this question :

Using his advice, you can ( hackily ) traverse the complex grob objects and alter elements at will (but remember ggplot was kinda designed to take those decisions out of your hands for very good reason - you might make some bad graphical design choices!).

Try and work out how the below works and you will be able to extend it to change all manner of other elements. The $gp is basically the grid equivalent of par options for base plotting.

gplot <- ggplotGrob( plot )
nms <- lapply( gplot$grobs , function(x) names( x[]$children ) )
grbs <- which( sapply( lapply( nms , function(x) grepl( "strip.background.rect" , x ) ) , any ) == 1 )
cl <- c("#2b8cbe","#fc9272","#2b8cbe")
for ( i in 1:length(grbs) ){
    col <- cl[i]
    i <- grbs[i]
    gplot$grobs[[i]]$children[[1]][]$gp$fill <- col

}
require(gridExtra)
grid.arrange( gplot )

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM