Drew Steen Drew Steen - 3 months ago 16
R Question

Minus as an exponent in plotmath (in ggplot2 legend)

I'm trying to make a legend in a

ggplot2
plot that contains a minus sign as an exponent (with no other characters in the exponent). However, I can't figure out the
plotmath
syntax.

It seems like the following would work:

expr1 <- expression(paste("text", main[sub]^{-}))

ggplot(mpg, aes(x=cty, y=hwy, colour=drv)) + geom_point() +
scale_colour_discrete(labels=c(expr1, "b", "c"))


(And it does work if we say
expr1 <- expression(paste("text", main[sub]^{super}))
. Is there an escape character or something for minus signs in
plotmath
?

42- 42-
Answer

You are almost certainly going to need to put quotes around that minus sign, because it would otherwise be expected to be an infix operator and as such require arguments before and after it. Add a small test case if that does not solve the problem.

Escaping does not work in plotmath. In particular you cannot use "\n" as an end-of-line/newline marker (as is documented in the help(plotmath) page.

This also succeeds:

expr1 <- expression(paste("text", main[sub]^{phantom()-phantom()}))

I had never before tried using phantom preceding and succeeding an infix operator, but it seems acceptable to interpreter. Plotmath expressions do get parsed and need to conform to R-parsing rules. See ?Syntax. As noted in comments, using "-" as a prefix operator to a single phantom() also succeeds because the minus sign can be used as either a unary-minus or a binary-minus:

expr1 <- expression(paste("text", main[sub]^{-phantom()}))
Comments