Search code examples
rplotgridlines

How do I draw gridlines using grid() behind the plot?


My code is:

plot(series,xlab="Tempo",ylab="Participação em %",ylim=c(10,55),type="s")
grid()

which yields:

enter image description here

I'm pretty sure that there is an easy way of drawing these gridlines behind the plot, but I couldn't find any in the grid() documentation. Any help would be appreciated.


Solution

  • Use the panel.first argument in plot:

    plot(1:50, 1:50, xlab="Tempo",ylab="Participação em %",ylim=c(10,55), 
         type="s", panel.first=grid())
    

    enter image description here

    A hackier way, if we didn't have panel.first would be: Run the plot code, but use type="n", which will prevent the data from being plotted. Add the grid. Then use lines() to plot the data on top of the grid.

    plot(1:50, 1:50, xlab="Tempo",ylab="Participação em %",ylim=c(10,55), type="n")
    grid()
    lines(1:50, 1:50, type="s")