R语言:仅在图形内部绘制网格线

R language: plot grid lines only inside the graph

我正在尝试删除图表外的所有网格线。我注意到 R 中的行为不是确定性的,即有时网格线仅在图形内部(如我所愿),但有时它跨越整个图形(参见 sample)。我想总是把网格线放在里面。

我阅读了网格 manual,但找不到这样做的选项。 abline() 还会在整个图中放置网格线。

我使用的代码是

plot(xrange, yrange, type="n", xlab="X", ylab="Y", xlim=c(200,1500), ylim=c(0,10000))
...
grid(lty=3, col="gray")

感谢任何帮助。谢谢,

诺迪尔

当我遇到这个问题时,是因为 par(xpd=TRUE) 在代码中的某处。在使用 grid() 之前尝试设置 par(xpd=FALSE),然后设置 par(xpd=TRUE)。示例代码用于生成相同的两个图,其中一个具有延伸到绘图区域之外的网格线。

set.seed(1)
x <- rnorm(100)
y <- rnorm(100)

# scatter plot with gridlines inside
par(xpd=FALSE) # do not plot outside the plot region
plot(x,y)
grid(lwd=2)

# scatterplot with gridlines outside the region
par(xpd=TRUE) # plot outside the plot region
plot(x,y)
grid(lwd=2)