By using the grid method you may add a grid to the current graph. By default the grid lines will align with the tick marks on the corresponding default axis. Although by using the arguments nx and ny you may set the number of cells of the grid in x and y direction. It is not possible to tell it explicitly where to place those lines. The following example shows a standard grid and some grids with a defined number of grid cells.
x <- c(1,2,3,4,5,6)
y <- c(3,6,9,4,3,4)
par(mfrow=c(2,2))
plot(x,y, main = ’standard‘)
grid()
plot(x,y, main = ‚2 grid cells‘)
grid(2,2)
plot(x,y, main = ‚4 grid cells‘)
grid(4,4)
plot(x,y, main = ‚6 grid cells‘)
grid(6,6)
Grid arguments
To customize your grid you may use the following parameters:
col: color of the grid lines.
lty: line type of the grid lines.
lwd: line width of the grid lines
The following example shows how to use these parameters.
x <- c(1,2,3,4,5,6)
y <- c(3,6,9,4,3,4)
plot(x,y, type = ‚l‘, lwd = 4)
grid(col = ‚lightgreen‘, lty = ‚dashed‘, lwd = 2)
Draw grid behind plot data
In R the order of commands matters. Therefore, in the previous example, the plot line is behind the grid lines because it was created last. But you cannot easily change the order because the grid needs the plot to know where to draw the grid lines. So how can we manage this case? We can create the empty plot first, add the grid and then add the plot content. Following you will see the adapted example. The command par(new=TRUE) enables overplotting. So the second plot is created on top of the first one.
x <- c(1,2,3,4,5,6)
y <- c(3,6,9,4,3,4)
plot(x,y, type = ’n‘)
grid(col = ‚lightgreen‘, lty = ‚dashed‘, lwd = 2)
par(new=TRUE)
plot(x,y, type = ‚l‘, lwd = 4)
Draw grid lines on custom positions
If you want to create an irregular grid with lines at some defined positions you cannot use the grid function. But in this case you may use abline as an alternative. You will find an example for the abline command in a previous article.