1

I try to use geom_richtext of the "ggtext" package to create my labels and I want to plot a number and a letter on top of each other. But I don't know whether this is even possible with "ggtext" yet. I could only achieve the desired layout with the use of a complicated combination of expression, atop, and paste. Nonetheless, I would strongly prefer an HTML solution, if there is one. Any ideas?

Here is what I was able to code so far:

library(tibble)
library(ggplot2)
library(ggtext)

dummy <- tibble(this = "A", that = 1)

my_label1 <- "*p* = 0.05<br>&omega;<sub>*p*</sub><sup>2</sup>: large"

dummy %>%
  ggplot(., aes(this, that)) +
  theme_void() +
  geom_richtext(
    aes(0, 0, label = my_label1),
    size = 10, label.colour = "grey", hjust = 0
    )
#> Warning in text_info(label, fontkey, fontfamily, font, fontsize, cache): unable
#> to translate '<U+03C9>png128.4527559055118' to native encoding
#> Warning in text_info_cache[[key]] <- info: unable to translate
#> '<U+03C9>png128.4527559055118' to native encoding


my_label2 <- expression(atop(paste(italic("p")," = 0.05 "), paste(omega [italic("p")] ^"2", ": large")))

dummy %>%
  ggplot(., aes(this, that)) +
  theme_void() +
  geom_label(
    aes(0, 0),
    label = my_label2, parse = T, size = 10
    )
#> Warning in is.na(x): is.na() auf Nicht-(Liste oder Vektor) des Typs 'expression'
#> angewendet

Created on 2022-11-17 with reprex v2.0.2

zephryl
  • 14,633
  • 3
  • 11
  • 30
maRvin
  • 249
  • 1
  • 11
  • 1
    Since ggtext uses HTML/CSS tags, you might look at answers on doing this in HTML (e.g., [\[1\]](https://stackoverflow.com/q/1580696/17303805), [\[2\]](https://stackoverflow.com/questions/3742975/subscript-and-superscript-for-the-same-element)). That said, ggtext implements only some CSS tags and I haven't tested these. – zephryl Nov 17 '22 at 16:46
  • I know how to use CSS with R Markdown, but I don't know whether they can be used in a plain .R script. – maRvin Nov 17 '22 at 17:04
  • 2
    It can be within ggtext -- e.g., `"Label with inline red text"`. However I've been playing with the answers I linked without much luck. I think among other things, position elements like `top` may not be implemented in ggtext. – zephryl Nov 17 '22 at 17:09
  • I also had no success with the inline CSS tags from the links. So it might not work with "ggtext" yet. I think I have to stick to the bulky ```expression``` for the time being. – maRvin Nov 17 '22 at 17:30

0 Answers0