从ggplot对象分析多边形的R点

问题描述 投票:0回答:1

我正在运行一个QAQC协议,有一个带有x和y坐标的点数据集和一个多边形,我想确定这些点是否在多边形内(多边形外的点应该被标记为假值)。

point.in.polygon却给出了这样的输出,即没有点在多边形内。

我想我的问题一定是ggplot或geom_build中的点的问题,因为我用我的多边形和随机点值广泛地尝试了point.in.多边形函数。

下面是一个可复制的例子,希望有人能指出我到底是哪里出了问题。

多边形的值。

mean_aug_temp_ref=13.8
mean_aug_sd_ref=3.906242
sd_aug_temp_ref=3.083504
sd_aug_sd_ref=1.699699


#and these are my point values

data=data.frame("x"=c(16.17419355,16.79354839,16.37096774,15.7483871, 17.07741935,16.18387097,
  16.38064516,15.91612903,15,14.42580645,14.91935484,15.5,15.78709677,15.88709677,
  23.9,18.22258065,15.51612903,14.8516129,14.93548387,15.93225806,17.6483871,16.57741935,
  16.27419355,15.79354839,15.70322581,15.23548387,15.8516129,16.95483871,16.58064516,
  16.25806452,18.13225806,16.46774194,16.10645161,14.80322581,16.85806452,13.24516129,
  14.28387097,14.56451613),"y"=c(3.422182138,3.325302421,5.216263575,4.932097849,3.247799051,3.658370522,
  3.498499886,3.901150792,4.236607552,3.960090498,3.781208758,3.783591385,
  3.693390973,3.806386412,0.48730997,2.301078,3.721169197,4.045304928,3.684483053,
  3.41859195,2.901957554,3.415018251,3.466360853,3.79302042,3.739892688,4.178312743,
  4.041067269,2.901698087,2.832576457,3.230205585,3.063566527,3.068009,3.13238139,
  4.655432875,3.282535421,4.515352932,3.374136237,4.564639348))

test_object=ggplot(data=data, aes(x, y))+
  geom_point()+ #the point layer
  #ellipse for 5 times the sd for mean and sd of reference values
  geom_ellipse(aes(a=sd_aug_sd_ref*5, x0=mean_aug_temp_ref, b=sd_aug_temp_ref*5, y0=mean_aug_sd_ref, angle=0))

built <- ggplot_build(test_object)$data
points <- built[[1]] #first list element are the points
ell <- built[[2]] #second list element is the ellipse

dat <- data.frame(
  data[,1:2], #first two columns are the coordinates
  in.ell = as.logical(point.in.polygon(point.x=points$x, point.y=points$y, pol.x=ell$x, pol.y=ell$y)))

r ggplot2 sp point-in-polygon
1个回答
0
投票

问题的发生是因为这条线。

ell <- built[[2]]

如果你检查这个数据帧,你会发现它实际上有38个椭圆的副本(每个点一个)。这是由以下原因造成的 geom_ellipse 是创建的。所以你的 "椭圆 "实际上是一个38循环的循环。解决办法是过滤掉,这样你就只得到一个椭圆的副本。

ell <- built[[2]][built[[2]]$group == built[[2]]$group[1],] 

dat <- data.frame(
        data[,1:2], #first two columns are the coordinates
        in.ell = as.logical(point.in.polygon(points$x, points$y, pol.x=ell$x, pol.y=ell$y)))

dat$in.ell
#>  [1]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
#> [13]  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
#> [25]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
#> [37]  TRUE  TRUE

你可以看到除了第15个元素之外的所有元素都在椭圆内。

© www.soinside.com 2019 - 2024. All rights reserved.