【问题标题】:create random points inside a shape in r在 r 中的形状内创建随机点
【发布时间】:2021-10-16 01:05:54
【问题描述】:

我正在尝试为一个项目模拟一些数据,基本上我需要绘制一个不规则的椭圆形,然后在该形状内制作一堆随机点,我完全不知道如何这样做。

现在,我制作了一个样条形状,然后在其上绘制了一堆点。有没有办法找到重叠?或者更好的是,只在预制形状的范围内生成随机点?

(如果有更好的开始方式,请随意放弃我的代码 - 也许它需要某种空间对象?)

set.seed(2)
shape <- data.frame(
  x     = c(2, 3, 2, 3, 2, 1, 0, 1),
  y     = c(1, 3, 5, 7, 9, 7, 5, 3 )
)

scatter = data.frame(
  x = rnorm(100, mean = 1.5, sd = .6),
  y = rnorm(100, mean = 5, sd = 2)
)


ggplot(data = shape, 
       aes(x=x,y=y)) +
  ggforce::geom_bspline_closed(fill = "transparent", color = "black") +
  geom_point(color = "blue") +
  coord_equal() +  
  geom_point(data = scatter, shape = "*", size=3)

【问题讨论】:

  • 我认为您可以通过使用runif 创建您的xy data.frame 来将更多样本哄骗到您的椭圆within,并为每个样本设置最小值和最大值?runif。跨度>

标签: r random simulation spatial


【解决方案1】:

我会推荐sf 包,因为它是为空间数据和执行空间操作而设计的。下面是一个在多边形内生成随机点的小例子:

library(ggplot2)

polygon =
  # The syntax for creating a polygon with sf is a little strange.
  # It has to be a list of matrices and the first point has to be 
  # repeated as the last point (2, 1).
  list(
    matrix(
      c(2, 1, 3, 3, 2, 5, 3, 7, 2, 9, 1, 7, 0, 5, 1, 3, 2, 1),
      ncol=2, byrow=T
    )
  ) 

# Create an sf polygon
polygon = sf::st_polygon(polygon)
# Sample 50 random points within the polygon
points = sf::st_sample(polygon, size=50)

# Plot using the ggplot geom_sf function.
ggplot() + 
  geom_sf(aes(), data=polygon) + 
  geom_sf(aes(), data=points)

如果您需要点的坐标,您可以简单地将 sf 点对象转换为 data.framepoints %&gt;% sf::st_coordinates() %&gt;% as.data.frame()

【讨论】:

【解决方案2】:

在 spatstat 中,多边形被用作点模式的观察窗口。 您可以对此类对象进行大量几何运算 (owin)。可能是 这样的东西很有用:

library(spatstat)
#> Loading required package: spatstat.data
#> Loading required package: spatstat.geom
#> spatstat.geom 2.2-2.002
#> Loading required package: spatstat.core
#> Loading required package: nlme
#> Loading required package: rpart
#> spatstat.core 2.3-0.003
#> Loading required package: spatstat.linnet
#> spatstat.linnet 2.3-0
#> 
#> spatstat 2.2-0       (nickname: 'That's not important right now') 
#> For an introduction to spatstat, type 'beginner'
W1 <- ellipse(a=5, b=2, centre=c(2,7), phi=80*pi/180)
W2 <- ellipse(a=5, b=2, centre=c(2,3), phi=-80*pi/180)
W <- union.owin(W1, W2)
plot(W, lwd=3, main = "")

Wplus <- dilation(W, 1)
plot(Wplus, lwd=3, main = "")

有很多方法可以在窗口内对点进行采样(参见章节 在?spatstat 中创建和操作数据)。例如。完全随机或 非常规则的间隔:

plot(runifpoint(50, win = Wplus))

plot(rSSI(r = 1, n = 50, win = Wplus))

【讨论】:

    猜你喜欢
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多