Last active
August 30, 2024 02:37
-
-
Save swo/a7a91f509a193cdd3df225fbeec5b005 to your computer and use it in GitHub Desktop.
Italics in ggplot facet labels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
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
Hi. Is label1 supposed to be short_label? I was wondering if you could provide some context for the options in the tibble function.
I'm working on a wonderfully similar issue, trying to italicize parts of the facet labels. This seems to be a shortcoming in ggplot and I've tried just about everything.
My plot code is below and my facet labels consist of: shigella, ttr, campy, ybbw, and ec which I want to show up as "EIEC/_Shigella_spp.", "Salmonella spp.", "Campylobacter jejuni", and "Escherichia coli" for the last two. This is where I am having issues.
Any input or insight/clarification would be appreciated!!