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

时间:2015-01-27 12:54:07

标签: r bar-chart r-grid

我在grid()内使用barplot()。因为我希望将条形图绘制在网格的顶部,所以我使用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 个答案:

答案 0 :(得分:3)

我认为这可能属于内部:
 &#34; panel.first:在设置绘图轴之后但在进行任何绘图之前要评估的“表达式”。这对于绘制背景网格或散点图平滑非常有用。 请注意,这可以通过延迟评估来实现:从其他绘图方法传递此参数可能无法正常工作,因为它可能过早评估&#34;

因此,最好的方法是通过3个步骤绘制barplot

# 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)

答案 1 :(得分:2)

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