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

1

2

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

Tedesco answered 8/3, 2013 at 9:13 Comment(0)
M
3

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.

Medici answered 8/3, 2013 at 10:8 Comment(2)
Nice workaround,... I thought there is n easier way. Anyway, first generating the plotmath-command, and then parsing it, is still intuitive,...Tedesco
Yes, I tried to find a way to directly concatenate the two expressions (the one with alpha and the pretty10exp output) but couldn't figure it out without building a character string as a prior step like here.Medici

© 2022 - 2024 — McMap. All rights reserved.