【问题标题】:How plot bars on top of grid lines when using barplot?使用 barplot 时如何在网格线上绘制条形图?
【发布时间】:2015-03-26 02:24:21
【问题描述】:

我在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)

【问题讨论】:

    标签: r bar-chart r-grid


    【解决方案1】:

    我认为这可能属于:
    "panel.first: 在设置绘图轴之后但在进行任何绘图之前要评估的“表达式”。这对于绘制背景网格很有用或散点图平滑。请注意,这通过惰性评估起作用:从其他绘图方法传递此参数可能不起作用,因为它可能评估得太早了"

    因此,最好的方法可能是分 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)
    

    【讨论】:

    • 谢谢凯丝。所以没有办法配置 panel.first 来完成这项工作?
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2014-06-14
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      • 2021-01-07
      • 2021-11-12
      相关资源
      最近更新 更多