0

I would like to be able to make superscripts inside a glue() function:

   glue::glue("{seq(0, 1500, by = 250)} μg/m^3")

In this way the m^3 is not evaluated, so I tried to do something like this:

   glue::glue("{seq(0, 1500, by = 250)} μg/{expression(m^3)}")

What I want to do with it, is to use it as the label argument in a scale_x_continuous() function in ggplot2.

Giulia
  • 279
  • 1
  • 4
  • 14

1 Answers1

4

Given your end goal is to format something in {ggplot2} you can use the {ggtext} package to apply markdown formatting to your labels:

library(tibble)
library(ggplot2)

your_sequence <- seq(0, 1500, by = 250)

labels <- glue::glue("{your_sequence} μg/m^3")

data <- tibble(x = your_sequence,
               y = sample(100:120, 7),
               labels = labels)

ggplot(data, aes(x = x, y = y)) +
  geom_point() +
  scale_x_continuous(breaks = your_sequence, labels = labels) +
  theme(axis.text.x = ggtext::element_markdown())

The trick is in applying ggtext::element_markdown() to the axis.text.x parameter of your theme().

Doing it this way you also don't need to add the expression inside your glue::glue() code.

I hope this helps!

  • For anyone else out there looking for a way to put superscript or subscript inside glue, outside of ggplot, you can create an object containing the superscript font and pass that to glue. i.e. `super <- "m^3^"; glue("{seq(0, 1500, by = 250)} μg/{super}")`. I'll also note that depending on how you are rendering the output, you may need to use "^3^" not "^3" to get the superscript. – ESELIA Jun 09 '23 at 14:05
  • Or if you are looking for a way to put super or subscript inside a glue object within geom_text, this solution works: https://stackoverflow.com/a/55264215/9154433 – ESELIA Jun 10 '23 at 18:15