Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grid line consistent with ticks on axis

Tags:

graph

r

gridlines

People also ask

What are ticks on axis?

A tick is a short line on an axis. For category axes, ticks separate each category. For value axes, ticks mark the major divisions and show the exact point on an axis that the axis label defines. Ticks are always the same color and line style as the axis.

Should tick marks be inside or outside graph?

William S. Cleveland, in his excellent book The Elements of Graphing Data , recommends that tick marks should point outwards 'because ticks that point inward can obscure data'.

Should grid lines always be present on graphs?

Grid lines are rarely needed in graphs to help readers assign accurate numeric values to the data; the approximate values that can be perceived without the aid of grid lines are almost always adequate.


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") 

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:

plot(x = 1:10, y = rnorm(10, 5, 2), xlim=c(1, 10), ylim=c(1, 10), panel.first=grid())

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:

plot(x = 1:10, y = rnorm(10, 5, 2), xaxp=c(1, 10, 10), yaxp=c(1, 10, 10), axes=FALSE)
axis(1, 1:10)
axis(2, 1:10)
abline(h=1:10, v=1:10, col="gray", lty=3)

grid example

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:

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

xaxp <- par("xaxp")
yaxp <- par("yaxp")

abline(v=seq(xaxp[1], xaxp[2], (xaxp[2]-xaxp[1])/xaxp[3]), lty=6, col = "cornsilk2")
abline(h=seq(yaxp[1], yaxp[2], (yaxp[2]-yaxp[1])/yaxp[3]), lty=6, col = "cornsilk2")

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,

The problem is that grid is putting nx grid lines in the user space, but plot is adding 4% extra space on each side. You can take control of this. Adding xaxs="i", yaxs="i" to your plot will turn off the extra space. But then your upper right point will be cut off, so you need to change the xlim and ylim values and change nx to match