I am embarrassed to ask this simple question, but has been in kicking my mind for several days whenever I create a plot:
plot (x = 1:10, y = rnorm (10, 5, 2))
grid (10,10, lty = 6, col = "cornsilk2")
I want to position the grids right at where axis are labelled, i.e. at 2, 4, 6, 8, 10 in x axis and similarly 3, 4, 5, 6, 7, 8 in y axis.
I want to automate the process as whenever the plot size changes the default label behaviour changes. See the following plot:
For reference, there is a way to control the grid and axes parameters directly from the plot() command, if we are not defining a custom tick interval:
The plot.default() documentation gives more information about these parameters.
When using a custom ticks interval, the easiest is to draw the grid using abline:
More information about custom tick intervals in this thread and here for grid alignment.
For posterity, here is the long-winded way of doing it manually:
From
?grid
description of thenx
andny
arguments:The answer provided here is much more straightforward, although you may dislike the lack of "free space" at each end of the axes. In brief,