Grid behind plot

No votes yet

You have a plot, and you want to draw a grid behind it. If you add the grid to the plot, using either

grid()
or
abline()
, the lines will be added on top of your plot, not behind it. I found the solution on the R-help mailing list, here. Redraw the plot after adding the grid, but first set
par(new=T)
so that it will be drawn on top of the old plot on the same device.

Here's an example:

(data is a data frame, data$X4 is a column in the data frame)

jpeg("fourthplace.jpg",height=600,width=700)
par(las=1)
par(mar=c(5.1, 22, 4.1, 2.5))
barplot(sort(table(data$X4)), horiz=T,xlim=c(0,12))
abline(v=seq(0,13,by=1),lty=3,col="grey")
par(new=T)
barplot(sort(table(data$X4)), horiz=T,xlim=c(0,12))
dev.off()

You could also use

grid()
. I prefer to use abline(). I tried
grid(nx=12,ny=NA) 
, but for some reason the lines were slightly off.