簡體   English   中英

使用 R 在兩個圓的交點處創建一個點

[英]Create a point at an intersection of two circles using R

我試圖在兩個圓的交點處在我的地塊上添加一個點。 在下面找到代碼示例。 如果無法添加點,了解交叉點的坐標可能對我有用。

A <- c(10, 11)
X <- c(0.245188, -1.199507)
Y <- c(-40.27914, -39.12006)
Di <- c(3.74, 5.18)
Mp <- c(19, 19)
df <- data.frame(Mp, A,  X, Y, Di)

library(ggplot2)
library(ggforce)

ggplot() + 
  geom_point(data=df, aes(X, Y)) +
  geom_circle(data=df, aes(x0 =X, y0 = Y, r = Di)) +
  geom_text(aes(X, Y, label = A), data = df, hjust = 1, vjust = 1) +
  coord_fixed() +
  theme_bw()

我嘗試了很多但找不到解決方案。 謝謝您的幫助。

編輯

我有一個更大的 data.frame 如何將其應用於我的 df。 下面是我的 df 的一個子集

A <- c(10, 11, 12, 7)
X <- c(0.245188, -1.199507,-42.31990, -39.98215)
Y <- c(-40.27914, -39.12006, -2.734103, 3.181081)
Di <- c(3.74, 5.18, 5.39, 5.11)
Mp <- c(19, 19, 19, 19)
df <- data.frame(Mp, A,  X, Y, Di)

'''

使用這篇文章https://math.stackexchange.com/a/1367732的推導,我希望這會對你有所幫助。 我沒有檢查是否確實存在交叉點,但我猜代碼運行得足夠快。 可能有更多基於交互功能的解決方案,但由於這是一個專門的問題,我希望我的解決方案對您有用。

A <- c(10, 11, 12, 7,9) #added another circle to test multiple intersections
X <- c(0.245188, -1.199507,-42.31990, -39.98215, -35)
Y <- c(-40.27914, -39.12006, -2.734103, 3.181081,-5)
Di <- c(3.74, 5.18, 5.39, 5.11,6)
Mp <- c(19, 19, 19, 19,19)
df <- data.frame(Mp, A,  X, Y, Di)

library(ggplot2)
library(ggforce)
library(tidyverse)

#https://math.stackexchange.com/a/1367732


combinations=combn(df$A,2) #find all potential combinations of circles in the data
remove(df_intersections) #if you rerun the script, the df would become ever longer ;-)
for(i in 1:ncol(combinations)){ #run the calculation for all circle combinations
  circle1=combinations[1,i]
  circle2=combinations[2,i]
  dfs=df[df$A==circle1|df$A==circle2,]

  #distance between circles
  dbc=sqrt(diff(dfs$X)**2+diff(dfs$Y)**2)

  dfs$sign=c(1,-1) #will have two rows in this case

  dfs=dfs %>% 
    mutate(x_intersect=0.5*(sum(X)) + ((diff(Di**2))/(2*dbc**2)) * (diff(X))*-1 + 
             0.5*sqrt((2*sum(Di**2)/dbc**2)-((diff(Di**2)**2)/dbc**4)-1)*(diff(Y))*sign,
           y_intersect=0.5*(sum(Y)) + ((diff(Di**2))/(2*dbc**2)) * (diff(Y))*-1 - 
             0.5*sqrt((2*sum(Di**2)/dbc**2)-((diff(Di**2)**2)/dbc**4)-1)*(diff(X))*sign)
  if(exists("df_intersections")){
    df_intersections=rbind(df_intersections,dfs)
  }else{
    df_intersections=dfs
  }
}

df_intersections=df_intersections %>% filter(!is.na(x_intersect)) #filter out combinations that don't intersect
ggplot(data=df) + 
  geom_point(aes(X, Y)) +
  geom_circle(data=df, aes(x0 =X, y0 = Y, r = Di)) +
  geom_text(aes(X, Y, label = A), data = df, hjust = 1, vjust = 1) +
  coord_fixed() +
  geom_point(data=df_intersections,aes(x=x_intersect,y=y_intersect),size=4, color="red")+
  theme_bw()

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM