[R] Format of numbers in plotmath expressions.

Uwe Ligges
2012-10-05T17:58:17Z

On 05.10.2012 09:30, Rolf Turner wrote:
>
> 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?


Not sure what is sexier here. I'd stay with

leg <- lapply(TH, function(x) bquote(list(theta == .(x))))
plot(1:10)
legend("bottomright", pch=1:5, legend=as.expression(leg))


Best,
Uwe Ligges



>
>          R. T.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.