Question

R determines panel order in xyplot() by alphabetic order (for strings), or level order (for factors). I have dates as text which I would like to display in chronological order, rather than alphabetical order.

x <- sample(1:10, 10, replace = TRUE)
y <- sample(1:10, 10, replace = TRUE)
# overlapping 2010 and 2011
date <- rep(as.Date("2010-01-01") + sort(sample(200:400, 5)), each = 2)
striptext <- format(date, "%d-%b ...")
df <- data.frame(x, y, date, striptext)

This works fine:

xyplot(y ~ x | date, data = df)

But this puts the dates out of order:

xyplot(y ~ x | striptext, data = df)

I don't want the full date in the strips, but I do want them in correct order. Is there any solution besides making striptext an ordered factor?

Was it helpful?

Solution

Set the levels of striptext explicitly and store it as a factor so that lattice doesn't have to do the coercion for you (which is where the levels end up in alpha order):

set.seed(1)
x <- sample(1:10, 10, replace = TRUE)
y <- sample(1:10, 10, replace = TRUE)
# overlapping 2010 and 2011
date <- rep(as.Date("2010-01-01") + sort(sample(200:400, 5)), each = 2)
striptext <- format(date, "%d-%b ...")
## set the levels explicitly
df <- data.frame(x, y, date, 
                 striptext = factor(striptext, levels = unique(striptext)))
xyplot(y ~ x | striptext, data = df)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top