Skip to content

Instantly share code, notes, and snippets.

@swo
Last active August 30, 2024 02:37
Show Gist options
  • Save swo/a7a91f509a193cdd3df225fbeec5b005 to your computer and use it in GitHub Desktop.
Save swo/a7a91f509a193cdd3df225fbeec5b005 to your computer and use it in GitHub Desktop.
Italics in ggplot facet labels
# Say I have some short-hand labels like "Ec/q",
# which actually stand for "E. coli & quinolones",
# but I want "E. coli" to be in italics
library(tidyverse)
n <- 100
tibble(
x = rnorm(n),
y = rnorm(n),
short_label = sample(c("Ec/q", "Sp/m"), size = n, replace = TRUE),
long_label = recode(
short_label,
"Ec/q" = "italic('E. coli')~'& quinolones'",
"Sp/m" = "italic('S. pneumoniae')~'& quinolones'"
)
) %>%
ggplot(aes(x, y)) +
geom_point() +
facet_wrap(~ long_label, labeller = label_parsed)
@swo
Copy link
Author

swo commented Mar 17, 2021

I'm surprised you found this old gist of mine!

I fixed that typo you noted and updated the syntax for more recent tidyverse versions. See below for how I would deal with your case. The key is learning about R expressions. This thread has some examples of different ways to do expressions. I like writing them as strings and having ggplot do all the parsing.

Tibble is just a way to make a data frame.

library(tidyverse)

data <- tibble(
  species = c("shigella", "ttr"),
  label = c("'EIEC/' * italic('Shigella') ~ 'spp.'", "italic('Salmonella') ~ 'species'"),
  x = c(1, 2),
  y = c(3, 4)
)

data %>%
  ggplot(aes(x, y)) +
  facet_wrap(vars(label), labeller = label_parsed) +
  geom_point()

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