문제

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

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top