我想用ggplot
画一个圆,然后在圆内散布点。我有代码(摘自这个答案 https://stackoverflow.com/a/68606605/6105259)这让我非常接近我想要的。但是,我希望点分散在圆内randomly,但现在我在中心周围出现了一个不需要的簇。
I saw a 类似的SO问答 https://stackoverflow.com/a/29061145/6105259,但它是用 c# 编写的,我不明白如何使其适应R
code.
到目前为止我的代码
以下代码定义了自定义可视化函数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)
Created on 2021-08-02 by the reprex package https://reprex.tidyverse.org (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)))
那么结果是:
知道如何避免聚类吗?我不一定想要完全均匀的分散。只是在圈子内随机。
所需输出
Adopted from this answer https://stackoverflow.com/a/29061071/6105259, the desired output should look something like: