Search code examples
rggplot2plotarearegion

how to confine plot region at exactly area


For example, I would like to plot a box with grids inside, the code show below:

plot(rnorm(10), rnorm(10), type = "n", asp = 1, xlim = c(0, 1), ylim = c(0, 1), axes = FALSE, pty = "s", bty = "o", xlab = "", ylab = "")
abline(h = seq(0, 1, 0.2), v = seq(0, 1, 0.2), col = "lightgray")
abline(a = 0, b = 1, col = "lightgray")
axis(1, seq(0, 1, 0.2), seq(0, 1, 0.2), pos = 0)
axis(2, seq(0, 1, 0.2), seq(0, 1, 0.2), pos = 0)

But the lines exceed the area (0, 0) to (1, 1), just like box with whisker. It may be the problem with plot region, and how can I confine the plot region to exactly area for example from (0, 0) to (1, 1)?

Thanks a lot!


Solution

  • plot(rnorm(10), rnorm(10), type = "n", asp = 1, xlim = c(0, 1), ylim = c(0, 1), 
         axes = FALSE, pty = "s", bty = "o", xlab = "", ylab = "")
    
    axis(1, seq(0, 1, 0.2), seq(0, 1, 0.2), pos = 0)
    axis(2, seq(0, 1, 0.2), seq(0, 1, 0.2), pos = 0, las=1)
    

    You can use clip to prevent annotations extending beyond the clip region. The four arguments determine the two coordinates of the rectangle for clipping.

    clip(0,1,0,1)
    abline(h = seq(0, 1, 0.2), v = seq(0, 1, 0.2), col = "lightgray")
    abline(a = 0, b = 1, col = "lightgray")