R_User
R_User

Reputation: 11082

Transform numbers with exponents to plotmath commands for beautiful legends in R

I'm trying to generate a beautiful legend in R plots. I have a factor=1e-5, that should appear nicely formatted in the legend. I found a nice function in the package sfsmisc, that transforms numbers to expressions. To add this expression to my bquote command, it seems that I need to transform itto a call. unfortunately, there are braces added at the end of the string (10^-5()).

Is there a way to avoid the addition of thoses braces? Or is there even an easier way to transform numbers to plotmaths commands for their use in legends? (without doing it manually)

factor = 1e-5
alpha = 1:10
omega = alpha^2 * factor

plot (
  alpha
  , omega
  , xlab=bquote(alpha)
  , ylab=bquote(omega)
  , type="b"
  )

text = expression()

# standard version
text[1] = as.expression(bquote(alpha%*%.(factor)))

# beautified version (use pretty10exp from sfsmisc package!?)
library("sfsmisc")
pretty = as.call(pretty10exp(factor, drop.1=T))
text[1] = as.expression(bquote(alpha^2%*%.(pretty)))

# add legend
legend("topleft", legend=text, pch=1, lty=1)

screenshot: red arrow points at the braces that should not be there

Upvotes: 2

Views: 567

Answers (1)

plannapus
plannapus

Reputation: 18759

Here's what you can do instead with function parse:

text <- paste("alpha^2%*%",parse(text=pretty10exp(factor,drop.1=T)),sep="")
text
[1] "alpha^2%*%10^-5" # which we then use as the expression in your call to legend
legend("topleft", legend=parse(text=text), pch=1, lty=1)

See ?parse for more explanation on how this work.

Upvotes: 3

Related Questions