Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

r - Align grid() to plot ticks

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...