[R] Adding points on top of lines in xyplot

Deepayan Sarkar deepayan.sarkar at gmail.com
Tue Nov 20 22:00:34 CET 2007


On 11/20/07, Dylan Beaudette <dylan.beaudette at gmail.com> wrote:

[...]

> Example:
> library(lattice)
>
> # generate some data:
> resp <- rnorm(100)
> pred <- resp*1.5 + rnorm(100)
> d <- data.frame(resp=resp, pred=pred)
>
> # add a grouping factor:
> d$grp <- gl(4, 25, labels=letters[1:4])
>
> # plot: looks ok!
> main.plot <- xyplot(resp ~ pred | grp, data=d, panel=function(x,y, ...)
> {panel.xyplot(x, y, ...) ; panel.lmline(x,y, ...) })
>
> # however, we have some other information which needs to go in each panel
> # note that the dimensions (i.e. no of obs) are not the same as the original
> # data, and the values are different, but on the same scale
> resp.other <- rnorm(20)
> pred.other <- resp.other*1.5 + rnorm(20)
> d.other <- data.frame(resp=resp.other, pred=pred.other)
> d.other$grp <- gl(4, 5, labels=letters[1:4])
>
>
> The big question:
> Now that we have the main plot (main.plot) looking ok, how can we add the data
> from d.other to the frames of main.plot without using subset() for each level
> of our grouping variable?

I would say you are asking the wrong question. The right question is:
how do I manipulate my data so that it becomes easy to work with. Try

combined <- make.groups(d, d.other)

xyplot(resp ~ pred | grp, data=combined, groups = which,
       panel = panel.superpose,
       panel.groups = function(x,y, ...) {
           panel.xyplot(x, y, ...)
           panel.lmline(x,y, ...)
       })

Is that close to what you want? Does it extend to your real example?

-Deepayan


>
>
> # after some messing around, how about this:
> xyplot(resp ~ pred | grp, data=d, panel=function(x,y, ...)
> {
> panel.xyplot(x, y, ...)
> panel.lmline(x,y, ...)
> # now the other data:
> panel.superpose(d.other$pred, d.other$resp, groups=d.other$grp,
> col=c('red', 'blue', 'green', 'orange')[as.numeric(d.other$grp)], pch=16,
> subscripts=TRUE)
> }
> )
>
> #... hmm it doesn't look like the information from 'd.other' is being
> stratified into the panels setup in panel.xyplot() ...
>
> The main point to this rather contrived example is this :
>
> 1. i have a data frame with continuous predictions, the response, and the
> grouping variable -- which plot nicely with the default use of xyplot()
>
> 2. I would like to embellish each panel with the original response and
> predictor values to illustrate the relationship between the original data and
> the smooth, fitted curve.
>
> ideas?
>
> thanks!
>
> Dylan
>
>
> --
> 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