Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I write axis ticks in small capital using ggtext?

I want to write axis ticks in small capital using ggtext::element_markdown(). However, an attempt like <span class='font-variant: small-caps'>small capital here!</span> is in vain. Then, how should I achieve that effect?

MWE

enter image description here

library(tidyverse)

tribble(
  ~ f1, ~ f2, ~ mean,
  "a",  "SBJ",  1212,
  "a",  "OBJ",  1313,
  "p",  "SBJ",  1515,
  "p",  "OBJ",  1616
) |>
  mutate(
    f2 = fct_relevel(
      f2,
      c(
        "SBJ",
        "OBJ"
      )
    )
  ) |>
  ggplot(
    aes(
      x = f2,
      y = mean,
      fill = f1
    )
  ) +
  scale_x_discrete(
    labels = c(
      "NP <span class='font-variant: small-caps'>sbj</span>",
      "NP <span class='font-variant: small-caps'>obj</span>"
    )
  ) +
  geom_col(
    position = 'dodge',
    size = 1
  ) +
  theme(
    axis.text.x = ggtext::element_markdown()
  )

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Unfortunately the font-variant property is not supported by ggtext. According to the [docs] only (https://wilkelab.org/ggtext/articles/introduction.html):

The CSS properties color, font-size, and font-family are currently supported.

Hence achieving your desired result requires some manual work by converting your strings to uppercase and setting a small font size via ggtext.

BTW: The style is set via style not class.

ggplot(
  df,
  aes(
    x = f2,
    y = mean,
    fill = f1
  )
) +
  scale_x_discrete(
    labels = c(
      glue::glue("NP <span style='font-size: 6pt;'>{toupper('sbj')}</span>"),
      glue::glue("NP <span style='font-size: 6pt;'>{toupper('obj')}</span>")
    )
  ) +
  geom_col(
    position = "dodge",
    size = 1
  ) +
  theme(
    axis.text.x = ggtext::element_markdown()
  )

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading