[R] legend + expression

Marc Schwartz marc_schwartz at comcast.net
Sat Jun 9 00:12:21 CEST 2007


On Fri, 2007-06-08 at 17:27 -0400, Pedro Mardones wrote:
> Dear all;
> 
> A simple? question.
> 
> I'm having a problem with a math expression in the legend of a plot
> and I haven't found the way to get this to work, so any help will be
> appreciate. Basically I want to include in the plot is the R-squared
> and its numerical value, so I tried this:
> 
> R2c<-0.82879 # R-squared of calibration model
> plot(1:10,1:10)
> legend("topleft", legend=c(expression(R[c]^2==format(R2c,nsmall=2))))
> 
> Thanks for any hint
> 
> PM

Try this:

  R2c <- 0.82879

  plot(1:10,1:10)

  R2c.2 <- sprintf("%.2f", R2c)

  legend("topleft", legend = bquote(R[c]^2 == .(R2c.2)))


See ?bquote and if you search the list archives, there are more complex
examples of using 'plotmath' in legends.

Note also that 'nsmall' in format() does not fix the number of digits
after the decimal:

> format(0.82879, nsmall = 2)
[1] "0.82879"

See ?formatC and ?sprintf for better options.

HTH,

Marc Schwartz



More information about the R-help mailing list