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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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!
How would you do it inside geom_hline(aes(linetype = IPA))? It does not work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.