问题描述
我是 R 的初学者,我想旋转我绘制的正方形。 有没有旋转我的淹没形状的功能
我希望绘制的正方形旋转 45 度
rect(
xright = 10,ytop = 10,xleft = 0,ybottom = 0,density = 40,col = "lightblue",border = "lightblue"
)
解决方法
我不确定有没有办法直接使用 rect()
函数执行此操作,但您可以创建另一个函数来旋转角点的坐标:
rect_rot <- function(
xright = 10,ytop = 10,xleft = 0,ybottom = 0,density = 40,rot = 0,centerx = xleft + (xright-xleft)/2,centery = ybottom + (ytop - ybottom)/2,...){
x <- c(xright,xright,xleft,xright) - (xright-xleft)/2
y <- c(ytop,ybottom,ytop,ytop) - (ytop-ybottom)/2
coords <- cbind(x,y)
rads <- (-rot)*pi/180
R <- matrix(c(cos(rads),sin(rads),-sin(rads),cos(rads)),ncol=2)
newcoords = t(R %*% t(coords))
newx <- newcoords[,1] + centerx
newy <- newcoords[,2] + centery
polygon(newx,newy,...)
}
rot
参数以顺时针为单位,在函数中被转换为弧度以适用于 R 中的三角函数。椭圆 (...
) 是其他参数,可以向下传递到绘制矩形的 polygons()
函数。旋转围绕原点 (0,0) 旋转,因此最初坐标以原点为中心,然后默认移回与原始多边形相同的中心,尽管这可以通过 centerx
和centery
参数。以下是一些示例。
plot(c(-30,30),c(-50,50),type="n")
rect_rot()
rect_rot(rot=45,border="red")
rect_rot(rot=45,border="blue",centerx=20,centery=-10)
编辑
回答关于绘制菱形的问题,你可以这样做:
rhombus <- function(xleft,...){
x <- c(xleft,xleft + (xright-xleft)/2,xleft)
y <- c(ybottom + (ytop-ybottom)/2,ybottom + (ytop-ybottom)/2,ybottom + (ytop-ybottom)/2)
polygon(x,y,...)
}
plot(c(-30,type="n")
rhombus(0,10,border="red")