Independent strip themes for ggplot2 facet_wrap using multiple variables

Is it possible to have independent themes for each variable used in ggplot2 facet_wrap ?

Take this piece of code as an example:

 p1 <- ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_wrap(c("cyl", "drv"), labeller = "label_both") plot(p1) 

Chart output

I would like to have a top bar (โ€œcilโ€) with a different theme - say, in bold. In addition, I may need to make "drv" italics with a different type and font size. How can i do this?

I was thinking of something in the lines:

  p1 <- p1 + theme(strip.text.variable1 = element_text(face = 'bold'), strip.text.variable2 = element_text(face = 'italic', size = 8) ) 

Unfortunately, I could not find anything like this in the docs or previous questions.

Greetings

Edit: I put the question a little more general in order to provide additional assistance to the community.

+6
source share
1 answer

Allegedly, you have to create a new function based on label_both in order to return bold labels, but so far my attempts have ended with the terrible Error in variable[[i]] : subscript out of bounds .

An alternative to this is to create a function to create the desired label. This is similar to this answer . In this function, you add a prefix to the values โ€‹โ€‹of the variable and make them bold.

 make_labels = function(string, prefix = "cyl: ") { x = paste0(prefix, as.character(string)) do.call(expression, lapply(x, function(y) bquote(bold(.(y))))) } 

Now use this function in as_labeller for the variable "cyl" in facet_wrap . You want to change the default label from as_labeller to label_parsed so that the expression is parsed correctly. Use label_both for another variable.

 ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_wrap(c("cyl", "drv"), labeller = labeller(cyl = as_labeller(make_labels, default = label_parsed), drv = label_both)) 

enter image description here

+3
source

All Articles