Skip to content

Instantly share code, notes, and snippets.

@FlukeAndFeather
Created February 22, 2021 03:49
Show Gist options
  • Save FlukeAndFeather/5e2e7ea851dea14cb22f969792fa24cf to your computer and use it in GitHub Desktop.
Save FlukeAndFeather/5e2e7ea851dea14cb22f969792fa24cf to your computer and use it in GitHub Desktop.
Partially italicize ggplot tick labels
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