Nodir Kodirov
Nodir Kodirov

Reputation: 909

R language: plot grid lines only inside the graph

I am trying to remove all grid lines outside the graph. I noticed that behavior in R is not deterministic, i.e., sometimes grid lines are inside the graph only (as I want), but sometimes it spans an entire figure (see sample). I'd like to always put grid lines inside.

I read grid manual, but could not find an option to do so. abline() also puts grid lines across an entire figure.

The code I am using is

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

Any help is appreciated. Thanks,

Nodir

Upvotes: 1

Views: 3221

Answers (1)

Calvin
Calvin

Reputation: 1359

When I have had this problem it is because par(xpd=TRUE) is somewhere in the code. Try setting par(xpd=FALSE) before using grid() and then par(xpd=TRUE). The sample code was used to generate the same the two plots, one of which has the grid lines extending outside of the plot region.

enter image description here

enter image description here

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)

Upvotes: 1

Related Questions