如何在 Shiny app R 编程中旋转正方形?

how can I rotate square in Shiny app R programming?

我是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, 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) 旋转,因此最初坐标以原点为中心,然后默认移回与原始多边形具有相同的中心,尽管这可以通过 centerxcentery 参数。这里有几个例子。

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")