Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么lines函数关闭R中的路径?_R_Graphics - Fatal编程技术网

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

为什么lines函数关闭R中的路径?,r,graphics,R,Graphics,目标:给定两个点,找到连接它们的弧的坐标并绘制。 实现:一个函数用于查找圆弧点(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 <

目标:给定两个点,找到连接它们的弧的坐标并绘制。 实现:一个函数用于查找圆弧点(
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))

circleFun我可以回答您关于
lines
函数的问题,但我将让您自己来解决如何修复
circleFun
以产生预期的行为:

lines()
按点在数据中出现的顺序连接点。此外,仅当第一个点再次包含在数据末尾时,路径才会关闭。下图说明了此行为

par(mfrow=c(1, 2))

plot(x=c(-1, 0, 1), y=c(-1, 1, -1), xlim=c(-2, 2), ylim=c(-2, 2),
     type="l", asp=1)
points(x=c(-1, 1), y=c(-1, -1))

plot(x=c(-1, 0, 1, -1), y=c(-1, 1, -1, -1), xlim=c(-2, 2), ylim=c(-2, 2),
     type="l", asp=1)
points(x=c(-1, 1), y=c(-1, -1))

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

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

circleFun+1:此函数还有一个优点,即它可以从一个输入点绘制到另一个输入点。如果将圆中的点数减少到(比如)10,则可以看到OP的函数不包括绘图中的任一端点,而这一个包含。