How do stripes overlap over grid lines when using barplot?

I use grid() inside barplot() . Since I want the columns to appear on top of the grid, I use the panel.first argument. However, the grid lines do not correspond to the ticks of the y axis. Can someone tell me how to solve this problem? My code looks 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) 
+5
source share
2 answers

I think this may fall inside:
"panel.first: a" is an expression that will be evaluated after the chart axes are set up, but before any plotting occurs. This can be useful for drawing background grids or smoothing out diffusion. Please note that this works with a lazy assessment: passing this argument to other plot methods may not work, as it can be evaluated too soon. "

So, perhaps the best way to do this is to draw a 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) 
+3
source

You can try adding a grid to the graph after setting the axis, that is, removing the panel.first argument and adding grid(nx=NA, ny=NULL) after adding the axis

+2
source

Source: https://habr.com/ru/post/1212001/


All Articles