Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aligning grid lines to axis ticks in lattice graphics

Tags:

r

lattice

Is there a way to align grid lines if they are chosen custom? By default, panel.grid(h=-1,v=-1) does the job, but I'd like to refine the grid according to the axis ticks. Setting h and v to negative lengths of axis ticks doesn't always work.

Update: Below is an example. I would like to achieve that horizontal grid lines match the y-axis ticks. Currently half of horizontal grid lines are missing.

library(lattice)

G <- cut(trees$Girth, seq(8, 22, by = 3))
p <- xyplot(Height ~ Volume | G, data = trees,
          scales = list(x = list(alternating = 3, at = seq(10, 60, by = 5)),
                        y = list(alternating = 3, at = seq(65, 85, by = 2.5))),
          panel = function(x, y, ...){
              panel.grid(v = -11, h = -9)
              panel.xyplot(x, y, ...)})
print(p)

What I currently get is this:

enter image description here

like image 944
Tentresh Avatar asked Mar 16 '14 05:03

Tentresh


1 Answers

If you want ticks and grid lines at places other than those returned by pretty, then don't use panel.grid; instead use panel.abline, with your custom at sequences.

library(lattice)

G <- cut(trees$Girth, seq(8, 22, by = 3))
x.at = 5*(2:12)
y.at = 2.5*(26:34)
p <- xyplot(Height ~ Volume | G, data = trees,
          scales = list(x = list(alternating = 3, at = x.at),
                        y = list(alternating = 3, at = y.at)),
          panel = function(x, y, ...){
              panel.abline(v = x.at, h = y.at, col="lightgrey")
              panel.xyplot(x, y, ...)})
print(p)

And don't forget to set the colour to something suitably light.

enter image description here

The limitation with panel.grid is mentioned deep down in help(panel.grid):

h, v
For panel.abline, these are numeric vectors giving locations respectively of horizontal and vertical lines to be added to the plot, in native coordinates.

For panel.grid, these usually specify the number of horizontal and vertical reference lines to be added to the plot. Alternatively, they can be negative numbers. h=-1 and v=-1 are intended to make the grids aligned with the axis labels. This doesn't always work; all that actually happens is that the locations are chosen using pretty, which is also how the label positions are chosen in the most common cases (but not for factor variables, for instance). h and v can be negative numbers other than -1, in which case -h and -v (as appropriate) is supplied as the n argument to pretty.

(My italics for emphasis).

One more wrinkle

If you have applied a transformation to an axis with a scale list, you have to apply the same transformation to the at vector that you supply to panel.abline - I don't know how to get this to happen automatically.

like image 198
Thruston Avatar answered Oct 23 '22 13:10

Thruston