Created
February 22, 2021 03:49
-
-
Save FlukeAndFeather/5e2e7ea851dea14cb22f969792fa24cf to your computer and use it in GitHub Desktop.
Partially italicize ggplot tick 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
library(tidyverse) | |
# Start with some dummy data | |
whale_data <- tribble( | |
~species, ~prey, ~order, | |
"B. musculus", "krill", 5, | |
"B. physalus", "fish", 3, | |
"B. physalus", "krill", 4, | |
"M. novaeangliae", "fish", 1, | |
"M. novaeangliae", "krill", 2 | |
) %>% | |
mutate(a = runif(nrow(.)), | |
b = a - runif(nrow(.)), | |
c = a + runif(nrow(.))) %>% | |
# Create a new column with the proper species/prey format | |
mutate(tick_labels = fct_reorder( | |
str_glue("italic(\"{species}\") ~ \"({prey})\""), | |
order | |
)) | |
# `labels = parse(text = ...` in scale_x_discrete() converts text to plotmath | |
ggplot(whale_data, aes(x = paste(species, prey), y = a)) + | |
geom_pointrange(aes(ymin = b, ymax = c)) + | |
scale_x_discrete(labels = parse(text = levels(whale_data$tick_labels))) + | |
theme_minimal() + | |
theme(axis.text.x = element_text(angle = 45, hjust = 1), | |
axis.title.x = element_blank()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment