In this recipe, we will learn how to add and customize grid lines to graphs.
We will use the base graphics for this recipe, so all you need to do is run the recipe at the R prompt. It is good practice to save your code as a script for use again later.
Let's use the city rainfall example again to see how we can add grid lines to that graph:
rain<-read.csv("cityrain.csv") plot(rain$Tokyo,type="b",lwd=2, xaxt="n",ylim=c(0,300),col="black", xlab="Month",ylab="Rainfall (mm)", main="Monthly Rainfall in Tokyo") axis(1,at=1:length(rain$Month),labels=rain$Month) grid()
It's as simple as that! Adding a simple default grid just necessitates calling the grid()
function without passing any arguments. The grid()
function automatically computes the number of cells in the grid and aligns with the tick marks on the default axes. It uses the abline()
function (that we will see again in the next recipe) to draw the grid lines.
We can specify the location of the grid lines using the nx
and ny
arguments, corresponding to vertical and horizontal grid lines, respectively. By default, these two arguments are set to NULL
, which results in the default grid lines in both X and Y directions. If we do not wish to draw grid lines in a particular direction, we can set nx
or ny
to NA
. If nx
is set to NA
, no vertical grid lines are drawn; if ny
is set to NA
, no horizontal grid lines are drawn.
The default grid lines are very thin and light-colored; they can barely be seen. We can customize the styling of the grid lines using the lwd
, lty
, and col
arguments:
grid(nx=NA, ny=8, lwd=1,lty=2,col="blue")
13.58.21.119