0

From ggplot2's reference manual, of label_both:

library(ggplot2)
mtcars$cyl2 <- factor(mtcars$cyl, labels = c("alpha", "beta", "gamma"))
p <- ggplot(mtcars, aes(wt, mpg)) + geom_point()

# Displaying both the values and the variables
p + facet_grid(. ~ cyl, labeller = label_both)

enter image description here

This will give us facet strips with both variable name and its values. However, say if I want to change the appearance of the variable name, but not change the values, e.g.:

expression(italic(cyl))

So that I can get a cyl: 4 instead of cyl: 4, is it possible to do it using the labeller function?

Tianjian Qin
  • 525
  • 4
  • 14
  • If you add `+ theme(strip.text = element_text(face = "italic"))` to your command your labels would be italic, but for e.g. "cyl: 4" both the "cyl" and the "4" will be italic; would this solve your problem, or do you want "cyl" to be italic and "4" to be 'regular'? – jared_mamrot Dec 06 '22 at 03:14
  • @jared_mamrot I actually want to label the variable name with some Greek letters and superscripts, so changing the theme cannot solve my actual problem – Tianjian Qin Dec 06 '22 at 03:17
  • I answered a ~similar question here: https://stackoverflow.com/a/74623026/12957340, would that approach work for your situation? – jared_mamrot Dec 06 '22 at 03:18
  • @jared_mamrot seems pretty similar, I will try it tomorrow to see if it works, thank you! – Tianjian Qin Dec 06 '22 at 03:20

1 Answers1

1

After a look at the docs and the source code label_both has no parse option. But similar to the approach in the answer referenced by @jared_mamrot in his comment you could use as_labeller to create a custom labeller for which you use label_parsed.

library(ggplot2)

mtcars$cyl2 <- factor(mtcars$cyl, labels = c("alpha", "beta", "gamma"))
p <- ggplot(mtcars, aes(wt, mpg)) +
  geom_point()

p + facet_grid(. ~ cyl,
  labeller = as_labeller(
      ~ paste0("italic(cyl):", .x), label_parsed
  )
)

stefan
  • 90,330
  • 6
  • 25
  • 51