Grid line consistent with ticks on axis

jon picture jon · Nov 10, 2011 · Viewed 50.9k times · Source

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.

enter image description here

I want to automate the process as whenever the plot size changes the default label behaviour changes. See the following plot:

enter image description here

Answer

joran picture joran · Nov 10, 2011

From ?grid description of the nx and ny arguments:

When NULL, as per default, the grid aligns with the tick marks on the corresponding default axis (i.e., tickmarks as computed by axTicks)

plot (x = 1:10, y = rnorm (10, 5, 2)) 
grid (NULL,NULL, lty = 6, col = "cornsilk2")