[R] multiple lty on same panel in xyplot

Deepayan Sarkar deepayan.sarkar at gmail.com
Wed Aug 5 20:22:47 CEST 2009


On 8/5/09, Jacob Wegelin <jacob.wegelin at gmail.com> wrote:
> I would like to use lattice graphics to plot multiple functions (or groups
>  or subpopulations) on the same plot region, using different line types "lty"
>  or colors "col" to distinguish the functions (or groups).
>
>  In traditional graphics, this seems straightforward: First plot all the data
>  using 'type="n"', and subsequently execute a series of "points" or "lines"
>  commands, one for each different group or function.
>
>  What is the elegant way to do this using xyplot?
>
>  To make this concrete, consider the following toy example:
>
>  k<- 10
>  x<- (1:k)/3
>  yM<-6 + x^2
>  yF<-12 + x^(1.5)
>  xNA<-x[length(x)]
>
>  # Insertion of NA row is necessary to prevent a meaningless line
>  # from being drawn from the females to the males across the entire plot.
>
>  DAT<-data.frame(
>  x=c(x, xNA, x)
>  ,
>  y=c(yF, NA, yM)
>  ,
>  sex=c( rep(0, k ), 0,  rep(1, k))
>  )

It's much simpler in lattice, and you don't need to play such tricks. Option 1:

xyplot(yM + yF ~ x, type = "l", auto.key = list(points = FALSE, lines = TRUE))

and if you want to control lty etc:

xyplot(yM + yF ~ x, type = "l", auto.key = list(points = FALSE, lines = TRUE),
       par.settings = simpleTheme(lty = c(2, 3)))


Option 2 (a bit more work, but less mysterious under the hood):

DAT<-
    data.frame(x = c(x, x), y=c(yF, yM),
               sex= rep(c("Female", "Male"), each = length(x)))

xyplot(y ~ x, data = DAT, groups = sex, type = "l")

-Deepayan

[...]

>  This draws both men and women in the same color and line type. Instead, I
>  want to specify different "col" and "lty" values for the two groups.
>
>  More generally, does a reference exist that explains this kind of thing,
>  with examples? I have not yet found an answer to this question in Paul
>  Murrell's book. Does Deepayan Sarkar's _Lattice_ go into that kind of
>  detail?

Yes, but for a shorter introduction, see

http://www.bioconductor.org/workshops/2008/PHSIntro/latticeLab.pdf

-Deepayan




More information about the R-help mailing list