Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align grid() to plot ticks

Tags:

plot

r

When adding ticks to a plot (more ticks than default), how does one get the grid() to align the grid to the ticks?

plot(1:10,las=1,xaxp  = c(0, 10, 10),xlim=c(0,10), ylim=c(0,10))
grid(lwd=2, nx=10, ny=10)

enter image description here

Tried changed the xlim and different numbers for the nx arg in grid (number of cells), but the grid simply doesn't line up.

Related, but doesn't answer question: Aligning grid lines in R, bReeze package

Related, and uses workaround: Align grid with ticks

Is the workaround the most efficient option?

like image 677
Minnow Avatar asked Feb 02 '17 18:02

Minnow


2 Answers

You could use abline to draw grids. You can specify where the grids should be with h (for horizontal lines) and v (for vertical lines)

#Plot
plot(1:10,las=1,xaxp  = c(0, 10, 10),xlim=c(0,10), ylim=c(0,10))
#Add horizontal grid  
abline(h = c(0,2,4,6,8,10), lty = 2, col = "grey")
#Add vertical grid
abline(v = 1:10,  lty = 2, col = "grey")

Another workaround is to use axis where tck value is 1. With axis, you can specify where the grids should be with at

#Plot
plot(1:10,las=1,xaxp  = c(0, 10, 10),xlim=c(0,10), ylim=c(0,10))

#Add horizontal grid  
axis(2, at = c(0,2,4,6,8,10), tck = 1, lty = 2, col = "grey", labels = NA)

#Add vertical grid
axis(1, at = 1:10, tck = 1, lty = 2, col = "grey", labels = NA)

#Add box around plot
box()

enter image description here

like image 118
d.b Avatar answered Oct 20 '22 21:10

d.b


The problem is that grid is putting nx grid lines in the user space, but plot is adding 4% extra space on each side. You can take control of this. Adding xaxs="i", yaxs="i" to your plot will turn off the extra space. But then your upper right point will be cut off, so you need to change the xlim and ylim values and change nx to match. Final code is:

plot(1:10,las=1,xaxp  = c(0, 10, 10),xlim=c(0,11), ylim=c(0,11),
    xaxs="i", yaxs="i")
grid(lwd=2, nx=11, ny=11)

Gridded plot

like image 41
G5W Avatar answered Oct 20 '22 23:10

G5W