[R] question in xyplot of lattice

Deepayan Sarkar deepayan.sarkar at gmail.com
Fri Dec 7 21:37:14 CET 2007


On 12/7/07, Aimin Yan <aiminy at iastate.edu> wrote:
> I try to make a xyplot like the following:
>
> xyplot(y1+y2~id|groups, ...)
>
> I also want to calculate cor(y1,y2) in each group, print it on each panel.
>
> Does anyone know how to write panel function for this?

This should work:

panel.cor <- function(x, y, groups, subscripts, ...)
{
    require(grid)
    g <- groups[subscripts]
    ug <- unique(g)
    stopifnot(length(ug) == 2)
    y1 <- y[g == ug[1]]
    y2 <- y[g == ug[2]]
    grid.text(label = round(cor(y1, y2), 3),
              x = unit(0.5, "npc"),
              y = unit(0.5, "npc"))
}

xyplot(y1 + y2 ~ id | groups,
       panel = function(...) {
           panel.xyplot(...)
           panel.cor(...)
       })

See ?grid.text for finer control over placement.

-Deepayan



More information about the R-help mailing list