ggplot italicize single character in axis tick labels- previous posts suggestions not working

50 Views Asked by At

I am trying to italicize a single letter in x-axis tick labels in ggplot. I have tried all the previous suggestions in the posts found on stackoverflow, using multiple approaches

these are the different methods tried:

xlabs<-c("Scrabble <br><i>N</i>=1101", # not italic, all shown in tick label
         "Dig<br>*N*=70", # not italic, all shown in tick label
         "Eat\n*N*=190",# not italic, all shown in tick label
         expression(paste("Forage\n",italic("N"),"=772")),#is italic, messes up text position
        "Move\n<i>N<i>=22",# not italic, all shown in tick label
         expression("Post-vig\n"~italic(N)~"=82")) # is italic, messes up text position

see image plot axis for output

enter image description here

I would just like a solution with the "N" italicized and the tick mark label formatting not messed up. Similar to the final example from this post:

Italic letters in generated axis tick labels

enter image description here

Thanks in advance!

1

There are 1 best solutions below

0
stefan On BEST ANSWER

Add a helper column to your data where you paste the total number of counts to the category label. To get the counts italicized I use ggtext, i.e. wrap in an <i> tag and add the line break via <br>. Then map this column on the x aes and set axis.text.x = ggtext::element_markdown() .

Using a minimal reproducible example using ggplot2::mpg:

library(ggplot2)
library(dplyr, warn = FALSE)

mpg |>
  add_count(class) |>
  mutate(x = paste0(class, "<br><i>n = ", n, "</i>")) |>
  ggplot(aes(x, hwy)) +
  geom_boxplot() +
  theme(
    axis.text.x = ggtext::element_markdown()
  )