[R] Aligning Grid Lines with Date Ticks in Trellis Plot

Peter Ehlers ehlers at ucalgary.ca
Thu Nov 25 01:31:47 CET 2010


On 2010-11-24 06:59, Elliot Joel Bernstein wrote:
> I know this issue has been discussed before, but I hoped the advent of pretty.Date would resolve it. In the following code, the first plot produces misaligned vertical grid lines, while in the second plot they are properly aligned. Is there any way to get something along the lines of the first call to produce properly aligned grid lines?
>
> X<- data.frame(date=seq(as.Date("1990/01/01"), as.Date("2010/11/24"), by=1))
> X$value<- rnorm(length(X$date))
>
> ## This produces grid lines not aligned with the date ticks
>
> xyplot(value ~ date, data=X,
>         panel = function(...) {
>           panel.grid(v=-1,h=-1,col="black")
>           panel.xyplot(...)
>         })
>
> ## This produces grid lines aligned with the date ticks
>
> xyplot(value ~ date, data=X,
>         panel = function(...) {
>           panel.abline(v=pretty(X$date, 5))
>           panel.grid(v=0,h=-1,col="black")
>           panel.xyplot(...)
>         })
>

Here are a couple of ways:

  xyplot(value ~ date, data=X, grid=TRUE)  ## or use type="g"

or

  xyplot(value ~ date, data=X,
         panel = function(x,y,...) {
           panel.grid(v=-1, h=-1, col=3, x=x, y=y,...)
           panel.xyplot(x,y,...)
         })

or, putting the grid call inside the panel.xyplot:

  xyplot(value ~ date, data=X,
         panel=function(x,y,...) {
           panel.xyplot(x, y,
                        grid=list(v=-1, h=-1,
                                 col=3, x=x, y=y), ...))
         })

Peter Ehlers

> Thanks.
>
> - Elliot



More information about the R-help mailing list