[R] Cbind() on the right-side of a formula in xYplot()

Dylan Beaudette debeaudette at ucdavis.edu
Tue Oct 27 22:08:52 CET 2009


On Monday 26 October 2009, Frank E Harrell Jr wrote:
> Dylan Beaudette wrote:
> > Hi,
> >
> > Using the latest rms package I am able to make nice plots of model
> > predictions +/- desired confidence intervals like this:
> >
> > # need this
> > library(rms)
> >
> > # setup data
> > d <- data.frame(x=rnorm(100), y=rnorm(100))
> > dd <- datadist(d)
> > options(datadist='dd')
> >
> > # fit model
> > l <- ols(y ~ rcs(x), data=d)
> >
> > # predict along original limits of data
> > l.pred <- Predict(l)
> >
> > # plot of fit and conf. int.
> > xYplot(Cbind(yhat, lower, upper) ~ x, data=l.pred, method='filled',
> > col.fill=grey(0.9), col=1, type='l')
> >
> > Is there any way in which I can turn this figure on its side, by plotting
> > x ~ y... something like this:
> >
> > # doesn't work
> > xYplot(x ~ Cbind(yhat, lower, upper), data=l.pred, method='filled',
> > lable.curves=FALSE, col.fill=grey(0.9), col=1, type='l')
> >
> > # standard lattice, but without the fancy filled area
> > xyplot(x ~ yhat + lower + upper, data=l.pred, type='l', lty=c(1,2,2),
> > col=1)
> >
> > Any suggestions? If it is not possible, then I will try and manually make
> > the figure with basic lattice functions.
> >
> > Cheers,
> > Dylan
>
> Dylan,
>
> Cbind is for the left hand side of the formula.  I suggest you look at
> one of the books that covers lattice graphics, or the online resources
> for lattice to customize this.  The output from Predict is suitable for
> several graphics models.
>
> Frank

Thanks Frank. I was able to cobble together a replacement; note that it 
depends on the original structure of my data, and is therefore not a general 
solution.

Cheers,
Dylan

panel.yx <- function(x, y, subscripts, groups, upper, lower, ...) {

# extract this panel's data
d <- data.frame(yhat=x, top=y, upper=upper[subscripts], 
lower=lower[subscripts], groups=groups[subscripts])

# levels in the groups, for color matching
ll <- levels(d$groups)

# add grid
panel.grid(h=-1, v=-1, lty=3, col=1)

# add conf. intervals
by(d, d$groups, function(d_i) {
# make conf.int polygon
panel.polygon(x=c(d_i$lower, rev(d_i$upper)), y=c(d_i$top, rev(d_i$top)), 
col=grey(0.85), border=NA, alpha=0.5)
})

# add main lines
by(d, d$groups, function(d_i) {
# lookup color
m <- match(unique(d_i$group), ll)
# add line
panel.lines(d_i$yhat, d_i$top, lwd=trellis.par.get('superpose.line')$lwd, 
col=trellis.par.get('superpose.line')$col[m])
})


}



-- 
Dylan Beaudette
Soil Resource Laboratory
http://casoilresource.lawr.ucdavis.edu/
University of California at Davis
530.754.7341




More information about the R-help mailing list