我不确定有没有办法直接使用 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, xleft, xright) - (xright-xleft)/2
y <- c(ytop, ybottom, 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 和 @987654331 更改@ 参数。下面是几个例子。
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, xright, ybottom, ytop, ...){
x <- c(xleft, xleft + (xright-xleft)/2, xright, xleft + (xright-xleft)/2, xleft)
y <- c(ybottom + (ytop-ybottom)/2, ytop, ybottom + (ytop-ybottom)/2, ybottom, ybottom + (ytop-ybottom)/2)
polygon(x, y, ...)
}
plot(c(-30, 30), c(-50, 50), type="n")
rhombus(0, 10, 0, 10, border="red")