Search code examples
rggplot2unicode

Superscript, multi line in ggplot label -- Unicode issue


The answer from this post addresses a spacing issue for ggplots with multi lines and exponents in the second line. Specifically something like this:

library(ggplot2)
library(magrittr)

iris %>% 
  ggplot(aes(x = Sepal.Length, y = Sepal.Length)) +
  geom_point() +
  labs(x = expression(paste('This is the first line of the x label\n', x^-1, ')')))

However, I can't seem to figure out how to get the superscript minus from unicode working. I tried all of these options. Here is an example that gets a minus sign but not a superscript minus sign:

iris %>% 
  ggplot(aes(x = Sepal.Length, y = Sepal.Length)) +
  geom_point() +
  labs(x = 'This is the first line of the x label\n(x\U2212\u00b9)')

Trying other unicode values yields a box in Rstudio like this (trying out \u207B):

enter image description here

Any help is appreciated!


Solution

  • Here are two options to achieve your desired result. The first ones uses atop and the second uses ggtext and an HTML <sup> tag:

    library(ggplot2)
    
    iris |>
      ggplot(aes(x = Sepal.Length, y = Sepal.Length)) +
      geom_point() +
      labs(x = expression(
        atop(
          "This is the first line of the x label",
          (x^{"\u2212" * 1})
        )
      ))
    

    
    library(ggtext)
    
    iris |>
      ggplot(aes(x = Sepal.Length, y = Sepal.Length)) +
      geom_point() +
      labs(x = "This is the first line of the x label<br>(x<sup>\u22121</sup>)") +
      theme(
        axis.title = ggtext::element_markdown()
      )