gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:04:38 24 4
gpt4 key购买 nike

我想用ggplot画一个圆,然后在里面散布点。我有代码( adopted from this answer )让我非常接近我想要的。但是,我希望这些点随机散布在圆圈内,但现在我在中心周围出现了一个不需要的簇。
我看到一个 similar 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)

创建于 2021-08-02 由 reprex package (v2.0.0)

应该很容易注意到每个圆圈中心周围的集群。我们如何随机排列圆内的点,以避免中心的簇?
我的尝试 sample()
我猜解决方案涉及修改 df_circular_points_scatter数据。但是,我不知道如何。我试图包装每个 df_circular_points_scatter带有 sample() 的列,但随后得到了超过圆周的点,并且总体上是“交叉”排列。
也就是说,如果我们用 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)))
那么结果是:
points_exceeding

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

期望输出
摘自 this answer ,所需的输出应类似于:
Sample output

最佳答案

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

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)

)
(参见 this 交叉验证问题)
结果:
enter image description here

关于r - 如何使用ggplot在圆内随机散布点,而不会围绕中心聚集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68619095/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com