R 使用条形图时,如何在网格线上绘制条形图?

R 使用条形图时,如何在网格线上绘制条形图?,r,bar-chart,r-grid,R,Bar Chart,R Grid,我正在barplot()的内部使用grid()。因为我想在网格顶部绘制条形图,所以我使用面板.first参数。但是,栅格线与y轴的记号不匹配。有人能告诉我如何解决这个问题吗?我的代码如下,谢谢 WRE <- c(1423, 41721) bp <- barplot(WRE, xaxt = 'n', xlab = '', yaxt = 'n', las = 3, width = 0.5, space = 1.5, main = paste("How You

我正在
barplot()
的内部使用
grid()
。因为我想在网格顶部绘制条形图,所以我使用
面板.first
参数。但是,栅格线与y轴的记号不匹配。有人能告诉我如何解决这个问题吗?我的代码如下,谢谢

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)

WRE您可以在设置轴后尝试将网格添加到绘图中,即删除
面板。首先
参数,然后添加
网格(nx=NA,ny=NULL)
在添加轴后

我认为这可能属于以下内容:
“panel.first:在设置打印轴之后但在进行任何打印之前要计算的‘表达式’。这对于绘制背景网格或散点打印平滑非常有用。请注意,这是通过延迟计算实现的:从其他打印方法传递此参数可能不起作用,因为它可能计算得太早。”

因此,最好的方法可能是分3步绘制
条形图

# 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)
#绘制条形图

谢谢你,凯丝。所以没有办法配置panel.first来执行此任务?