How do I draw gridlines using abline() that are behind the data?

前端 未结 4 1601
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 06:57

When I draw grid lines on a plot using abline() the grid lines are drawn over the data.

Is there a way to draw the abline() lines behind

相关标签:
4条回答
  • 2020-12-05 07:13

    Plot first with type="n" to establish coordinates. Then put in the grid lines, then plot again with your regular plot type:

    plot(x, y, col = 'red', type = 'n', lwd = 3, pch = 15)
    abline(h = seq(0, 10, .5), col = 'lightgray', lty = 3)
    abline(v = seq(0, 10, .5), col = 'lightgray', lty = 3)
    par(new=TRUE)
    plot(x, y, col = 'red', type = 'o', lwd = 3, pch = 15)
    

    I admit that I have always thought the name for that par parameter was "backwards."

    0 讨论(0)
  • 2020-12-05 07:17

    The panel.first argument of plot() can take a list or vector of functions so you can put your abline() calls in there.

    plot(1:4, panel.first = 
           c(abline(h = 1:4, lty = 2, col = 'grey') 
            ,abline(v = 1:4, lty = 2, col = 'grey')))
    
    0 讨论(0)
  • 2020-12-05 07:25

    Use plot() to set up the plotting window, but use type = "n" to not plot any data. Then do your abline() calls, or use grid(), and then plot the data using whatever low-level function is appropriate (here points() is fine).

    x <- seq(0, 10)
    y <- x
    plot(x, y, type = "n")
    abline(h = seq(0, 10, .5), col = 'lightgray', lty = 3)
    abline(v = seq(0, 10, .5), col = 'lightgray', lty = 3)
    points(x, y, col = 'red', type = 'o', lwd = 3, pch = 15)
    

    or

    ## using `grid()`
    plot(x, y, type = "n")
    grid()
    points(x, y, col = 'red', type = 'o', lwd = 3, pch = 15)
    

    See ?grid for details of how to specify the grid as per your abline() version.

    0 讨论(0)
  • 2020-12-05 07:31

    Another way of creating grid lines is to set tck=1 when plotting or in the axis function (you may still want to plot the points using points after creating the grid lines.

    0 讨论(0)
提交回复
热议问题