3

I'm trying to format the legend in my plot, but I have to use expression() because of greek and superscripts. However, when I want to display r^2 = 0.45, P<0.0001, I get r^2 = 0.45 P<1e-04, when I type in

legend(expression(r^2==0.9230~~P<0.0001))

I tried looking up the list() function but it doesn't help with the commas. I couldn't find anything on using decimals in the expression() function either.

Any suggestions would be appreciated.

Thanks

plannapus
  • 18,529
  • 4
  • 72
  • 94
crazian
  • 649
  • 4
  • 12
  • 24
  • For scientific notation, R uses a "penalty system". Check `?options` under `scipen`. When `options(scipen=HighNumber)`, it will be less inclined to use scientific notation - and more inclined at a negative number. Default is zero. In this instance, if you use paste as Josh is suggesting, it won't try to convert to scientific anyway. – Señor O Nov 02 '12 at 19:26

2 Answers2

13

You can use paste() (within the call to expression()) to splice together character strings and unquoted expressions. The unquoted bits will be evaluated using the special rules exhibited by example(plotmath) and demo(plotmath), while the character strings will be printed verbatim.

Here's an example (which also uses phantom(), because the < operator expects/needs something to both its left and its right):

plot(1)
legend(x = "topleft", 
       legend = expression(paste(r^2==0.9230, ",  ", P<phantom(), "0.0001")))

enter image description here

Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
  • A great tip, thank you @Josh O'Brien! Surprisingly, it only works with `paste`, not `paste0`. – Bob May 03 '23 at 02:51
  • 1
    @Bob Interesting point. I think it's because plotmath must have special rules for handling the symbol `paste` passed along to it by `expression()`, just as it special-cases things like `^`, `[]`, `_`, etc. The rules described in `?plotmath` really define a kind of mini-language in which `paste()` has a similar seeming but not actually the same meaning as it does in other R contexts. Does that make sense? – Josh O'Brien May 03 '23 at 17:09
  • Dear @Josh O'Brien -- Yes, that makes total sense! I am sure you are correct that the "mini-language" of `plotmath` only defines (or uses) its own version of `paste` and does not define `paste0`. Just thought it was an interesting tidbit, that had me a bit perplexed for a while and might be useful for others... Thanks again for the answer! – Bob May 03 '23 at 23:04
5

Here's an alternative way using substitute that avoids phantom:

plot(1)
options(scipen=10)
legend(x = "topleft", 
       legend = substitute(list(r^2 == r2, P < p), list(r2=0.923, p=0.0001)))

enter image description here

Matthew Plourde
  • 43,932
  • 7
  • 96
  • 113