为什么line函数关闭R中的路径?

Eme*_*mer 6 graphics r

目标:给出两点,找到连接它们的弧的坐标并绘制它. 实现:一个函数用于查找弧的点(circleFun),另一个用于绘制它(plottest).颜色显示路径的方向,从红色到绿色.

circleFun <- function(x,y)
{
  center <- c((x[1]+y[1])/2,(x[2]+y[2])/2)
  diameter <- as.numeric(dist(rbind(x,y)))

  r <- diameter / 2
  tt <- seq(0,2*pi,length.out=1000)
  xx <- center[1] + r * cos(tt)
  yy <- center[2] + r * sin(tt)
  res <- data.frame(x = xx, y = yy)

  if((x[1]<y[1] & x[2]>y[2]) | (x[1]>y[1] & x[2]<y[2])){
    res <- res[which(res$x>min(c(x[1],y[1])) & res$y>min(c(x[2],y[2]))),]
  } else {
    res <- res[which(res$x<max(c(x[1],y[1])) & res$y>min(c(x[2],y[2]))),]
  }
  return(res)
}

plottest <- function(x1,y1)
{
  plot(c(x1[1],y1[1]),c(x1[2],y1[2]),
       xlim=c(-2,2),ylim=c(-2,2),col=2:3,pch=20,cex=2,asp=1)
  lines(circleFun(x1,y1))
}

par(mfrow=c(2,2))
plottest(c( 1,-1),c(-1, 1))
plottest(c(-1, 1),c( 1,-1))
plottest(c(-1,-1),c( 1, 1))
plottest(c( 1, 1),c(-1,-1))
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述

问题:我无法弄清楚为什么lines函数关闭图[1,1]和[1,2]中的路径,而不是图[2,1]和[2,2].预期结果应该是所有数字与第二行的数字相同.

谢谢!

flo*_*del 6

像其他人说的那样.这就是说,这是一个更简单的函数版本,具有您期望的输出.

circleFun <- function(x, y) {

  center <- (x + y) / 2
  radius <- sqrt(sum((x - y)^2)) / 2
  angle  <- atan2((y - x)[2], (y - x)[1])
  direc  <- ifelse(abs(angle) > pi / 2, -1, 1)
  tt <- seq(0, direc * pi, length.out = 1000)

  return(data.frame(x = center[1] + radius * cos(angle + tt),
                    y = center[2] + radius * sin(angle + tt)))
}
Run Code Online (Sandbox Code Playgroud)

其中direc变量就是决定是否半圆顺时针或逆时针画.

打开半圆圈