作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想用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)
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)))
那么结果是:
最佳答案
你快到了。采样需要按以下步骤进行:
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 交叉验证问题)
关于r - 如何使用ggplot在圆内随机散布点,而不会围绕中心聚集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68619095/
我是一名优秀的程序员,十分优秀!