[R] lattice: option to sort x when type = l

Deepayan Sarkar deepayan.sarkar at gmail.com
Tue Jul 27 06:41:32 CEST 2010


On Mon, Jul 26, 2010 at 9:11 PM, Prasenjit Kapat <kapatp at gmail.com> wrote:
> Hi,
>
> (please Cc me)
>
> In xyplot (), type = "l" (or one that includes "l", *el*) is
> (generally) meaningful only when the 'x' variable is sorted. In
> practice, one either sorts the data frame before hand or writes a tiny
> panel function which sorts the supplied x and then calls the default
> panel.xyplot(). Trouble arises when there is a conditional variable as
> well as a groups argument.
>
> Of course, sorting the data frame before hand is the simplest
> solution. But, when one wishes to plot against multiple 'x' variables
> the data has to be sorted each time, which, to me, doesn't seem the
> "right" way (of course, a personal opinion). Hence a feature request
> to add a sort option when type = "l".
>
> Before giving a reproducible example, is there anything even simpler
> that I have missed?
>
> Example:
>
> Everything included:
>
>> source ('http://www.stat.osu.edu/~pkapat/miscl/Code4xyplot_sort_type_l.R')
>
> OR, step by step:
>
>> library (lattice)
>>
>> # toy data
>> D <- read.csv ('http://www.stat.osu.edu/~pkapat/miscl/Data4xyplot_sort_type_l.csv')
>>
>> # default behavior: obviously wrong
>> xyp1 <- xyplot (y ~ x/1000 | C, groups = G, data = D, type = "o", main = 'Wrong behavior, obviously')
>>


Here are two simple enough solutions:

## uses panel.average

xyplot(y ~ x/1000 | C, groups = G, data = D, type = c("p", "a"))

## more efficient, as no tapply involved

panel.xyplot.sorted <- function(x, y, ...)
{
    o <- order(x)
    panel.xyplot(x[o], y[o], ...)
}

xyplot(y ~ x/1000 | C, groups = G, data = D, type = "o",
       panel = panel.superpose,
       panel.groups = panel.xyplot.sorted)

-Deepayan



More information about the R-help mailing list