MeC
MeC

Reputation: 463

Superscript and subscript points in ggplot2

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

Upvotes: 2

Views: 1441

Answers (1)

eipi10
eipi10

Reputation: 93791

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

Upvotes: 1

Related Questions