[R] ltext, plotmath, and substitute

Deepayan Sarkar deepayan at stat.wisc.edu
Wed Apr 14 22:34:18 CEST 2004


On Wednesday 14 April 2004 11:13 am, Dave Atkins wrote:
> I am interested to use plotmath functions within a panel function but am
> having some problems getting the code right.  Within each panel I am
> plotting the data, fitting a regression line, and would like to print the
> regression equation. Here is a trivial example of what I'd like to do:
>
> # generate simple data
> tmp.df <- data.frame(id = rep(1:4, each=4),
> 			time = rep(1:4, 4),
> 			das = rnorm(16))
> # plot regression lines and print equations
> xyplot(das ~ time | as.factor(id), data = tmp.df, strip = T,
> 	   panel = function(x,y,...){
> 		 panel.coef <- round(coef(lm(y~x)), 2)
> 		 panel.grid()
> 		 panel.xyplot(x,y)
> 		 panel.lmline(x,y)
> 		 ltext(1.2, 1, pos = 4,
> 		   paste("Y = ",panel.coef[1]," + ",panel.coef[2],"*time",
> 			sep = ""), cex = 1.2)
> 		 },
> 	   layout = c(4,1,1), aspect = 2.5)
>
> The above works fine.  However, I'd like to make the equations more
> attractive by adding a hat over Y and an epsilon at the end, and this is
> where I have run into problems.  I experimented with expression() and
> paste() for a while without luck, and now believe I need to use
> substitute() (given some of the examples on the plotmath() help-page). 
> But, I can't get the code quite right.

Following example(plotmath), the following seems to work:


panel = function(x, y, ...) {
    panel.coef <- round(coef(lm(y~x)), 2)
    panel.grid()
    panel.xyplot(x,y)
    panel.lmline(x,y)
    ltext(1, 1, pos = 4, 
          as.expression(bquote(hat(Y) == .(panel.coef[1]) + 
          .(panel.coef[2]) * time + epsilon)))
}

The as.expression() is not necessary in text, but is in ltext.



Incidentally, ?bquote says 

Value:

     An expression

but, 

> is.expression(bquote(hat(y)))
[1] FALSE
> is.call(bquote(hat(y)))
[1] TRUE

Something should probably be changed.


Deepayan




More information about the R-help mailing list