如何使用ggplot在圆内随机散布点,而不会围绕中心聚集?

我想用来ggplot画一个圆,然后在里面散点。我有代码(从这个答案中采用)让我非常接近我想要的。但是,我希望点随机散布在圆圈内,但现在我在中心周围出现了一个不需要的簇。

我看到了一个类似的 SO question and answer,但它是在 c# 中,我不明白如何使其适应R代码。

到目前为止我的代码

下面的代码定义了一个自定义的可视化函数vis_points_inside_circle(),然后调用了4次,给出了4个使用我当前方法可视化的例子。

library(ggplot2)
library(ggforce)

## set up function
vis_points_inside_circle <- function(n) {
  
  # part 1 -- set up empty circle
  df_empty_circle <-
    data.frame(x = 0,
               y = 0, 
               r = 1)
  
  p_empty_circle <-
    ggplot(df_empty_circle) +
    geom_circle(aes(x0 = x, y0 = y, r = r)) + 
    coord_fixed() +
    theme_void()
  
  # part 2 -- set up points scatter
  r <- runif(n)
  th <- runif(n)
  
  df_circular_points_scatter <- 
    data.frame(x = r*cos(2*pi*th),  ## from @Ben's answer: https://stackoverflow.com/a/68606605/6105259
               y = r*sin(2*pi*th))
  
  
  # part 3 -- combine circle and points
  p_empty_circle +
    geom_point(data = df_circular_points_scatter, 
               aes(x = x, y = y))
}

## visualize
library(gridExtra)

set.seed(2021)
p1000_1 <- vis_points_inside_circle(n = 1000)
p1000_2 <- vis_points_inside_circle(n = 1000)
p2000_1 <- vis_points_inside_circle(n = 2000)
p2000_2 <- vis_points_inside_circle(n = 2000)


gridExtra::grid.arrange(p1000_1, p1000_2, p2000_1, p2000_2, nrow = 2)

由reprex 包( v2.0.0 )于 2021 年 8 月 2 日创建


应该很容易注意到每个圆圈中心周围的集群。我们如何随机排列圆内的点,以避免中心的簇?

我的尝试 sample()

我想解决方案涉及修改df_circular_points_scatter数据。但是,我不知道如何。我试图用 包裹每一df_circular_points_scattersample(),但后来得到了超过圆周的点,并且总体上是一个“交叉”排列。

也就是说,如果我们sample()像这样包装:

r  <- runif(n)
th <- runif(n)

df_circular_points_scatter <- 
    data.frame(x = sample(r*cos(2*pi*th)),  
               y = sample(r*sin(2*pi*th)))

那么结果是:


知道如何避免聚类吗?我不一定想要完全均匀的分散。只是在圈内随机。


期望输出

从这个答案中采用,所需的输出应该是这样的:

回答

你快到了。采样需要按以下步骤进行:

r <- runif(n)
th <- runif(n, 0, 2 * pi)
  
df_circular_points_scatter <- 
 data.frame(x = sqrt(r) * cos(th), 
            y = sqrt(r) * sin(th)

)

(请参阅有关交叉验证的此问题)

结果:


以上是如何使用ggplot在圆内随机散布点,而不会围绕中心聚集?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>