crazian
crazian

Reputation: 669

R: legend expression how to add comma between two values and how to supress scientific notation

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

Upvotes: 4

Views: 10159

Answers (2)

Matthew Plourde
Matthew Plourde

Reputation: 44614

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

Upvotes: 5

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162431

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

Upvotes: 14

Related Questions