On Tue, Oct 7, 2008 at 8:54 AM, baptiste auguie <ba208 at exeter.ac.uk>
wrote:> Dear list,
>
>
> I've been trying this for a few hours and I just don't understand
how
> lattice works with groups and subscripts.
>
> Consider the following example,
>
>
>
>> xx <- seq(1, 10, length=100)
>> x <- rep(xx, 4)
>> y <- c(cos(xx), sin(xx), xx, xx^2/10)
>> fact <- factor(rep(c("cos", "sin",
"id", "square"), each=100))
>> fact2 <- factor(rep(c("periodic", "not
periodic"), each=100))
>>
>> my.df <- data.frame(x=x, y=y, fact = fact, fact2 = fact2)
>>
>> head(my.df)
>>
>>
>> myColors <- c(2, 4)
>>
>> xyplot(y ~ x | fact, data = my.df, groups = fact2,
>> panel = panel.superpose,
>> panel.groups = function(..., group.number) {
>>
>> panel.xyplot(...)
>> #panel.xyplot( ..., col=myColors[group.number])
#
>> error
>>
>> })
>
>
> My aim is to assign a custom color to each group, but for some reason the
> col parameter is already given to panel.xyplot and I can't find where
it
> gets the values from.
It get's the values from the 'panel.superpose' function, of which
'panel.groups' is an argument. Both the documentation and source code
for 'panel.superpose' should make this clear.
>From what I understand, what you want should be as simple as (with a
small correction to your example):
xx <- seq(1, 10, length=100)
x <- rep(xx, 4)
y <- c(cos(xx), sin(xx), xx, xx^2/10)
fact <- factor(rep(c("cos", "sin", "id",
"square"), each=100))
fact2 <- factor(rep(c("periodic", "not periodic"),
each=200))
my.df <- data.frame(x=x, y=y, fact = fact, fact2 = fact2)
myColors <- c(2, 4)
xyplot(y ~ x | fact, data = my.df, groups = fact2, col = myColors, type =
"l")
The use of 'par.settings' is not compulsory, but would help if you
needed to add a legend; e.g.,
xyplot(y ~ x | fact, data = my.df, groups = fact2, type = "l",
par.settings = simpleTheme(col = myColors),
auto.key = list(lines = TRUE, points = FALSE))
If you insist on writing your own panel function, what you need is
xyplot(y ~ x | fact, data = my.df, groups = fact2,
panel = panel.superpose,
panel.groups = function(..., col.line, type, group.number) {
panel.xyplot(..., type = "l",
col.line = myColors[group.number])
})
As Bert pointed out, you are responsible for ensuring that argument
names are not repeated by capturing and overriding them.
All of this applies to your second, more complicated, example as well.
As for the order in which the groups are plotted, it is the order of
levels(fact2), which seemed to me the most obvious (or at least the
least surprising) choice. You are free to specify the order when you
create the factor; see ?factor to learn how.
-Deepayan