[R] Format of numbers in plotmath expressions.

Rolf Turner rolf.turner at xtra.co.nz
Fri Oct 5 09:30:13 CEST 2012


I want to do something like:

TH <- sprintf("%1.1f",c(0.3,0.5,0.7,0.9,1))
plot(1:10)
legend("bottomright",pch=1:5,legend=parse(text=paste("theta ==",TH)))

Notice that the final "1" comes out in the legend as just plain "1" and NOT
as "1.0" although TH is

[1] "0.3" "0.5" "0.7" "0.9" "1.0"

I can get plotmath to preserve "1.0" as "1.0" and NOT convert it to "1"
if I use substitute, as in

text(2,5,labels=substitute(list(theta == a),list(a=TH[5])))

but substitute doesn't work appropriately with vectors.

Can anyone tell me how to get a "1.0" rather than "1" in the legend?

Ta.

     cheers,

         Rolf Turner

P.S. Just figured out a way using sapply():

leg <- sapply(TH,function(x){substitute(list(theta == a),list(a=x))})
plot(1:10)
legend("bottomright",pch=1:5,legend=parse(text=leg))

Note that the use of "parse" (pace Thomas Lumley! :-) ) is required ---
"legend=leg" does NOT work.

Getting here required an enormous amount of trial and error.  And it seems
pretty kludgy.

Is there a sexier way?

         R. T.



More information about the R-help mailing list