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

8

我正在barplot()中使用grid()。因为我想要柱子绘制在格子上方,所以我使用了panel.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)
2个回答

5
我认为这可能属于以下内容:
"panel.first: 在绘制图轴设置之后但在任何绘图之前要评估的'表达式'。这对于绘制背景网格或散点图平滑非常有用。 请注意,这是通过惰性评估实现的:从其他绘图方法传递此参数可能不起作用,因为它可能会过早地评估"

所以,最好的方法可能是将barplot分为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)

谢谢 Cath。所以没有办法配置 panel.first 来完成这项工作吗? - Carter

2
在设置坐标轴之后,您可以尝试将网格添加到图中,即删除panel.first参数,并在添加坐标轴后添加grid(nx=NA, ny=NULL)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接