r - 为什么行函数会关闭 R 中的路径?

标签 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]。预期的结果应该是第二行的所有数字。
谢谢!

最佳答案

就像其他人说的那样。话虽如此,这是您的函数的一个更简单的版本,带有您的预期输出。

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

关于r - 为什么行函数会关闭 R 中的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15992205/

相关文章:

调试 R 中未由包导出的函数

根据给定索引用 dplyr 替换列中的值

在 Shiny 启动时跨选项卡呈现传单标记

wpf - 如何通过 WPF 中的坐标打开(更改颜色)单个像素

graphics - 纹理过滤和纹理采样有什么区别?

c++ - 为什么在使用 OpenGL 编译顶点着色器时会出现着色器编译器错误 #143、#160 和 #216?

r - 如何从 R 面板数据框中删除具有唯一 ID 的行?

regex - R 中 SQL LIKE 运算符的等价物

javascript - 形状内文本环绕的算法

java - 在 ActionListener 中添加图像