【问题标题】:Why lines function closes the path in R?为什么行函数会关闭 R 中的路径?
【发布时间】:2013-04-06 05:04:13
【问题描述】:

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

结果:

问题:我不明白为什么lines 函数会关闭图 [1,1] 和 [1,2] 中的路径,而图 [2,1] 和 [ 2,2]。预期的结果应该是第二行的所有数字。

谢谢!

【问题讨论】:

    标签: r graphics


    【解决方案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)))
    }
    

    direc 变量决定是顺时针还是逆时针绘制半圆。

    【讨论】:

    • +1:这个函数还有一个好处是它可以从一个输入点绘制到另一个输入点。如果您将圆中的点数减少到(例如)10,您可以看到 OP 的函数不包含图中的任何一个端点,而这个包含。
    【解决方案2】:

    我可以回答你关于 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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 2020-07-03
      • 1970-01-01
      • 2012-09-21
      • 1970-01-01
      相关资源
      最近更新 更多