用R旋转绘图网格

时间:2013-08-23 14:45:23

标签: r rotation gridlines

例如:

plot(1:10, 1:10)
grid(col="red")

是否可以围绕x轴和y轴(原点{0,0})的交点旋转红色网格,任意角度?这个例子并不意味着什么,但我想这样做。

1 个答案:

答案 0 :(得分:2)

无论如何,网格函数可能无法在基数R中执行此操作。它不是一个面向对象的绘图范式。我想你会接近abline

plot(1:10, 1:10,xlim=c(0,10), ylim=c(0,10))
sapply(seq(0,20,by=2), function(a) abline(a=a, b=-1,lty=3,col="red"))
sapply(seq(-10,10,by=2), function(a) abline(a,b=1,lty=3,col="red"))

enter image description here

这是坐标几何体的一个小应用,可以任意角度旋转。

angle=pi/8; rot=tan(angle); backrot=tan(angle+pi/2)
sapply(seq(-10,10,by=2), function(inter) abline(a=inter, 
                                                b=rot,lty=3,col="red"))
sapply(seq(0,40,by=2), function(inter) abline(a=inter, 
                                           b=backrot, lty=3,col="red"))

当angle = pi / 2时,这确实会中断,所以如果构建一个函数你可能想要检查这个,在这种情况下只需使用grid。我发现的一个问题是让间距令人愉悦。如果以相同的间隔在y轴和x轴上进行迭代,则会得到一组网格线的“压缩”。我认为这就是为什么这种方法在高角度下会崩溃的原因。

我认为更通用的解决方案可能是构建一组网格终点,这些终点跨越并超出绘图区域至少sqrt(2)因子,然后应用旋转矩阵。然后使用segmentslines。这是实施:

plot(1:10, 1:10,xlim=c(0,10), ylim=c(0,10)); angle=pi/8; rot=tan(angle);backrot=tan(angle+pi/2)
x0y0 <- matrix( c(rep(-20,41), -20:20), 41)
x1y1 <- matrix( c(rep(20,41), -20:20), 41)
# The rot function will construct a rotation matrix
rot <- function(theta) matrix(c( cos( theta ) , sin( theta ) ,
 -sin( theta ), cos( theta ) ), 2)
# Leave origianal set of point untouched but create rotated version
 rotx0y0 <- x0y0%*%rot(pi/8)
 rotx1y1 <- x1y1%*%rot(pi/8)
 segments(rotx0y0[,1] ,rotx0y0[,2], rotx1y1[,1], rotx1y1[,2], col="blue")
# Use originals again, ... or could write to rotate the new points
 rotx0y0 <- x0y0%*%rot(pi/8+pi/2)
 rotx1y1 <- x1y1%*%rot(pi/8+pi/2)
 segments(rotx0y0[,1] ,rotx0y0[,2], rotx1y1[,1], rotx1y1[,2], col="blue")

enter image description here