Minus as an exponent in plotmath (in ggplot2 legend)

落爺英雄遲暮 提交于 2019-12-12 12:38:57

问题


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?


回答1:


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()}))

We could also have used an empty character value as the item after the prefix minus: {-""}



来源:https://stackoverflow.com/questions/13636096/minus-as-an-exponent-in-plotmath-in-ggplot2-legend

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!