user defined panel function
Martin Henry H. Stevens wrote:
Mac OS 10.3.9 R framework v. 2.1.1
I am attempting to put a fitted curve into each panel of a lattice
graph, but am failing to do so. I have tried writing a very
sophisticated function to do so. The function seems to work when used
with plot(), but does not do so inside a panel function in xyplot().
Any pointers would be appreciated.
#The example data
fact <- gl(2,7)
x <- rep(1:7,2)
y <- c(1,1,2,3,2,3,4,1,2,1,2,3,3,4)
plot(jitter(y/6) ~ x)
# The following user defined function puts a curve (I believe the
correct one) into the scatterplot
panel.predglm <- function(x, y) {
model.trial <- glm(cbind(y,6-y) ~ poly(x,2),
family=quasibinomial(link="logit"))
xfit <- seq(1,7, length=21)
yfit <- predict(model.trial, newdata=data.frame(x=xfit),
type="response")
lines(xfit,yfit) }
panel.predglm(x, y)
# My attempt to use it in a lattice xyplot, however, fails. It draws a
curve which in most cases is outside the dimensions of the plot. I
suspect that the prediction is on the scale of the link functions.
library(lattice)
xyplot(y/6 ~ x|fact, ylim=c(0,.8),
panel=function(x, y,...) {
panel.xyplot(jitter(x),jitter(y))
panel.predglm(x,y) }
)
Any thoughts?
Two:
1. The "y" argument in your panel function ranges from 0 to 1 and not 0
to 6 as your plot example assumes.
2. You need to use llines in your panel function and not lines.
Here's a working example:
library(lattice)
fact <- gl(2,7)
x <- rep(1:7,2)
y <- c(1,1,2,3,2,3,4,1,2,1,2,3,3,4)
# The following user defined function puts a curve (I believe the
correct one) into the scatterplot
panel.predglm <- function(x, y) {
model.trial <- glm(cbind(y,6-y) ~ poly(x,2),
family=quasibinomial(link="logit"))
xfit <- seq(1, 7, length=21)
yfit <- predict(model.trial, newdata=data.frame(x=xfit), type="response")
llines(xfit,yfit)
}
xyplot(y/6 ~ x|fact, ylim=c(0,.8),
panel = function(x, y, ...) {
panel.xyplot(jitter(x), jitter(y))
panel.predglm(x, y * 6)
})