How plot bars on top of grid lines when using barplot?

Carter picture Carter · Jan 27, 2015 · Viewed 7.8k times · Source

I am using grid() inside of barplot(). Because I want the bars to be plotted on top of the grid, I use the panel.first argument. However, the grid lines do not match the ticks of y-axis. Can anyone tell me how to solve this problem? My code is like below, thanks.

WRE <- c(1423, 41721)

bp <- barplot(WRE, xaxt = 'n', xlab = '', yaxt = 'n', las = 3, width = 0.5,
              space = 1.5, main = paste("How You Compare", sep = ""), ylab = "",  
              names.arg = NA, col = c("red","blue"), cex.lab = 1, 
              panel.first = grid(nx = NA, ny = NULL))

axis(1, at=bp, labels=c("Average Claims", "Your Claims"),
     tick=FALSE, las=1, line=-1, cex.axis=1) 
axis(2, at=axTicks(2), sprintf("$%s", formatC(axTicks(2), digits=9, big.mark=",", width=-1)),
     cex.axis=0.9, las=2)

Answer

Cath picture Cath · Jan 27, 2015

I think this might fall inside:
"panel.first: an ‘expression’ to be evaluated after the plot axes are set up but before any plotting takes place. This can be useful for drawing background grids or scatterplot smooths. Note that this works by lazy evaluation: passing this argument from other plot methods may well not work since it may be evaluated too early"

So, probably, the best way to do it is draw the barplot in 3 steps:

# Draw the barplot
bp <- barplot(WRE, xaxt = 'n',xlab = '',yaxt = 'n',las = 3, width =0.5,space = 1.5, main=paste("How You Compare", sep=""), ylab="",  names.arg=NA,  col=c("red","blue"), cex.lab=1)
# add the grid
grid(nx=NA, ny=NULL)
# redraw the bars...
barplot(WRE, xaxt = 'n',xlab = '',yaxt = 'n',las = 3, width =0.5,space = 1.5, ylab="",  names.arg=NA,  col=c("red","blue"), cex.lab=1, add=T)
# Then you can add the axes
axis(1, at=bp, labels=c("Average Claims", "Your Claims"), tick=FALSE, las=1, line=-1, cex.axis=1) 
axis(2, at=axTicks(2), sprintf("$%s", formatC(axTicks(2), digits=9, big.mark=",", width=-1)), cex.axis=0.9, las=2)