在R中使用两个不同的x坐标向条形图添加一条线

时间:2014-03-11 23:15:42

标签: r

我有一个条形图,我想在这个条形图中添加一个图,但根据x轴的不同比例值,我不能正确地做到这一点。我希望第一条线穿过第一条线,第二条线穿过第二条和第三条,最后一条线穿过第四条和第五条。我怎么能在R? 我写了以下代码:

   barplot(c(2.5, .5, .5, 3.5, 6), names.arg=c("0-1","1-2", "2-3", "3-4", "4-5"))
   lines(c(1, 2, 3,4 ,5), c(3, .1, .1, 4, 6.5), lty=2, lwd=2)

1 个答案:

答案 0 :(得分:1)

理解你想要的东西有点复杂......我会尝试用这两个提示来帮助你:

  1. 绘制条形的x值由 barplot 函数返回。因此,要在后一个图中使用它们,您可以使用

    存储它们

    bp = barplot(...)

    并在调用

    后使用它们

    lines(bp, y.data, ...)

  2. 您会发现未绘制在条形图上方的线条部分,因为在使用条形图初始化视图时,默认情况下会裁剪y值。有几种可能的解决方法:

    bp = barplot(..., ylim=range(data)+c(-1,1) ) # to set the y-limits during the call to barplot

    或:

    lines(..., xpd=T) # to allow drawing in the plot margin

  3. 最后,下面显示了一个最小的工作示例:

    data = c(2.5, .5, .5, 3.5, 6)
    bp = barplot(data, names.arg=c("0-1","1-2", "2-3", "3-4", "4-5"),
                 ylim = range(data)+c(-1,1) )
    lines(bp, c(3, .1, .1, 4, 6.5), lty=2, lwd=2)
    

    enter image description here