[R] Question: xyplot panel configurations for Trellis package

hadley wickham
Fri, 27 Oct 2006 17:32:16 -0000

On 10/27/06, Zheleznyak, Anatoley <Anatoley.Zheleznyak at
constellation.com> wrote:
> Hi,
> I am new to R community and I have a question on panel configurations in
> the Trellis package.
> Particularly, I have the following code:
>
> require(lattice)
> plotTable <- NULL
> Date <- seq(as.Date("2006-11-01"),
as.Date("2009-12-01"), by = 1)
> nYear <- length(unique(format(Date,"%Y")))
> plotTable$Date <- as.Date(paste(unique(format(Date, "%Y-%m")),
"-01",sep
> = ""))
> nDate <- length(plotTable$Date)
> plotTable$Date <- rep(plotTable$Date, each = 10)
> plotTable$Date <- factor(format(plotTable$Date, "%b-%y"),
>
> levels=format(as.Date(unique(sort(as.character(plotTable$Date)))),
> "%b-%y"))
> plotTable$x <- rep(seq(1,10,by = 1), nDate)
> plotTable$y <- rep(seq(1,10,by = 1), nDate)
>
> xyplot(y ~ x| Date, data = plotTable,
>       panel=function(x,y){ panel.xyplot(x,y, type = "l", lwd = 3)
},
>       layout = c(12,nYear),
>       main = "Example of the panels by months")
>
> I would be interested to configure panels by years horizontally, so
> 2006, 2007, 2008, and 2009 all have different rows, and the months will
> be structured by columns,
> Thank you,

This is pretty easy to do with ggplot (although the basic principle,
creating month and year columns applies to lattice graphics as well):

install.packages("ggplot")
library(ggplot)

date <- seq(as.Date("2006-11-01"), as.Date("2009-12-01"),
by = 1)
date <- rep(date, each=10)

data <- data.frame(
  month = format(Date, "%m"),
  year = format(Date, "%y"),
  x = rnorm(length(date)),
  y = rnorm(length(date))
)

qplot(x, y, month ~ year, data=data)

Regards,

Hadley