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

时间:2013-04-13 19:52:11

标签: 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 <- 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))

结果:

enter image description here

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

谢谢!

2 个答案:

答案 0 :(得分: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)))
}

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

open semi-circles

答案 1 :(得分:3)

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

enter image description here

相关问题