2

I would like to add sub/superscript to some letters/characters in a ggplot2 point plot. I know how to do this in the axes, but in this case, because they are special characters, I define a character vector before plotting:

IPA=(c("ph", "th", "kh", "p", "t", "k", "ts", "tsh", etc.))

I want to plot letter combinations such as p^[h] and ts^[h] for the points in the graph but this syntax doesn't work (nor p^{h} or p^h). See graphic.

p <- ggplot(data, aes(x, y, label=IPA))
p + geom_text(size = 5) +
  theme(legend.position="none") +
  scale_shape_manual(values = IPA)

enter image description here

KoenV
  • 4,113
  • 2
  • 23
  • 38
MeC
  • 463
  • 3
  • 17

1 Answers1

1

You can convert the text to plotmath expressions and use parse=TRUE in geom_text. Below is an example with the built-in mtcars data frame. I've added your IPA values as a column to mtcars and then converted all of the instances of h to [h], and all of the instances of ts to t^s, which are, respectively, the subscript and superscript expressions in plotmath (see?plotmath for more on expressions; there are also lots of Stackoverflow questions related to mathematical annotation in R plots). parse=TRUE causes geom_text to render the h as a subscript.

mtcars$IPA = gsub("h", "[h]", IPA)
mtcars$IPA = gsub("ts", "t^s", mtcars$IPA)

ggplot(mtcars, aes(mpg, wt, label=IPA)) +
  geom_text(size=5, parse=TRUE) +
  theme_classic()

enter image description here

eipi10
  • 91,525
  • 24
  • 209
  • 285
  • Thank you! An alternative for anyone with a similar problem is to simply paste in the special characters to your vector before plotting. To ensure proper encoding, this is probably the best bet. Thank yoU! – MeC Dec 03 '17 at 18:03
  • How would you do it inside geom_hline(aes(linetype = IPA))? It does not work. – Alvaro Morales Apr 22 '21 at 17:57