3
votes

Could someone tell me how to add a text line to lattice plot.

My code is:

xyplot(Neff~Eeff,data=phuong,panel=mypanel,
       col="black",
       pch=18,xlab="Energy efficiency (%)",
       ylab = "Nitrogen efficiency (%)", main="(a)")

Here pane=mypanel is to add an abline. I want to add a linear regression equation between Eeff and Neff to their plot.

Thanks!

2
See ?panel.text, a function which you can add to your mypanel function.BenBarnes
It does not work for me. This is mypanel codes: mypanel<-function(x,y,...){ + panel.xyplot(...) + panel.abline(lm(Neff~Eeff,data=phuong)) + panel.text(30,30,labels=tp) + } Could you please help me to see it?hn.phuong
Please post a reproducible example so that it is easier to help you.BenBarnes
Thank you very much for your comments Benbarnes. My problem is in fact like this. As you can see in my codes above, I have two collumes of data: Eeff and Neff 1. I made a scatter plot using xyplot function 2. I used simple linear regression function: lm(Eeff~Neff, data=phuong) to find the regression equation: which is Eff=19.7 + 0.36 Neff NOW, what I want is to add "Eff=19.7 + 0.36 Neff" to the top-left corner of the scatter plot. Could you please help me? Thank you very much!hn.phuong
@hn.phuong this is still not reproducible. Ben provided a link. Check out his link. The basic idea is that in your original post we should be able to grab exactly the code you used and reproduce your error. You will want the data set to be as small as possible (maybe 5-10 rows) and still be able to reproduce the outcome. You can also use one of R's many built in data sets as an example.Tyler Rinker

2 Answers

8
votes

So, with reproducible data:

set.seed(1)

phuong <- data.frame(Eeff = rnorm(100,31))
phuong$Neff <- rnorm(100,19.7 + .36*phuong$Eeff)

# Create the lm object ahead of time
lm1 <- lm(Neff ~ Eeff, data = phuong)

# Create the character string that you want to print
tp <- sprintf("%s=%.1f + %.2f %s", all.vars(formula(lm1))[1],
  coef(lm1)[1], coef(lm1)[2], all.vars(formula(lm1))[2])

# Change the mypanel function to use the lm1 object
mypanel<-function(x,y,...){
  panel.xyplot(x, y, ...)
  panel.abline(lm1)
  panel.text(30,33,labels=tp)
}

library(lattice)

# and off we go.

xyplot(Neff~Eeff,data=phuong,panel=mypanel,
       col="black",
       pch=18,xlab="Energy efficiency (%)",
       ylab = "Nitrogen efficiency (%)", main="(a)")

enter image description here

4
votes
library(latticeExtra)

set.seed(1)

phuong <- data.frame(Eeff = rnorm(100,31))
phuong$Neff <- rnorm(100,19.7 + .36*phuong$Eeff)

xyplot(Neff ~ Eeff, data= phuong) + 
  layer(panel.ablineq(lm(Neff ~ Eeff, data= phuong), r.sq= TRUE, rot = TRUE))

enter image description here