[R] xyplot() with segments() superposed?

Deepayan Sarkar deepayan.sarkar at gmail.com
Mon Aug 13 18:35:25 CEST 2007


On 8/11/07, Yuelin Li <liy12 at mskcc.org> wrote:
> In the hypothetical example below, how do I add two segments() into
> the two panels, respectively?  Say segments(x0=5, y0=10, x1=5, y1=20)
> on the left and segments(x0=15, y0=-10, x1=15, y1=-2) on the right?
> Many thanks in advance,
>
> Yuelin Li.
>
> ps. part of the code came from a solution given by Deepayan Sarkar.
>
> -------------------
> library(lattice)
> set.seed(12345)
> x <- 0:20
> y.male.obs <- - 1.2 * x + 22 + rnorm(length(x), sd = 3)
> y.male.prd <- - 1.2 * x + 22
> y.fema.obs <- - 2.2 * x + 30 + rnorm(length(x), sd = 2)
> y.fema.prd <- - 2.2 * x + 30
> tdat <- data.frame(x = rep(x, 8),
>         y = rep(c(y.male.obs, y.male.prd, y.fema.obs, y.fema.prd), 2),
>         sex = rep(rep(c("m", "f"), each = 2*length(x)), 2),
>         cohort = rep(c("1970", "1980"), each = 4*length(x)),
>         source = rep(rep(c("obs", "prd"), each = length(x)), 4)  )
> xyplot(y ~ x | as.factor(cohort), data = tdat,
>        groups = interaction(sex, source),
>        type = c("p", "p", "l", "l"), distribute.type = TRUE)

If this is a one-off requirement, the simplest solution is:

xyplot(y ~ x | as.factor(cohort), data = tdat,
       groups = interaction(sex, source),
       type = c("p", "p", "l", "l"), distribute.type = TRUE,
       panel = function(...) {
           panel.xyplot(...)
           switch(panel.number(),
                  panel.segments(x0=5, y0=10, x1=5, y1=20),
                  panel.segments(x0=15, y0=-10, x1=15, y1=-2))
       })

This is not generalizable, but you haven't told us your general use case.

-Deepayan



More information about the R-help mailing list