There exists three main ways to add a grid to a plot in base R: using grid
, axis
or abline
functions.
grid
function
The grid
function is specifically designed to add grids to an existing plot. The function allows modifying the number of sections where to divide each axis with the nx
and ny
arguments, e.g. nx = 2
will create only a vertical line. You can also modify the color, width and type of the lines with the col
, lwd
and lty
arguments, respectively.
Option 1. Add grid to X and Y axis.
Option 2. Add grid only to Y-axis.
Option 3. Add grid only to X-axis.
Option 4. Customize the number of division sections with nx
and ny
arguments.
You may have noticed that the grid is added over the plot. In case you want to have the grid below your plot you have to add your plot over.
Option 1. You can use plot.new()
and par(new = TRUE)
. However, the grid won’t match the axis ticks.
Option 2. Instead of using plot.new()
you can use the plotting function to plot your data:
Option 3. If the plotting function you are using (like hist
, boxplot
or barplot
) supports the argument add
, set add = TRUE
instead of par(new = TRUE)
.
Note that you can add a background color and a grid at the same time as follows:
If your chart is a scatter plot you can add the points over the grid with the points
function.
axis
function
The axis
function allows customizing the axes of the plots. However, if you set tck = 1
the tick marks of the axes will create a grid.
abline
function
Similarly to axis
, abline
allows you to add grid lines at some values. The main benefit of this approach is that it doesn’t override the axis line, so you don’t have to use the box
function to solve it.
When the ticks of the plot are different from the default you can align them using the axis
or abline
functions in case that specifying nx
or ny
arguments of the grid
function doesn’t align them.
The same can be achieved making use of abline
instead of axis
.
See also