I am trying to plot data which is N number of samples inside a disk with radius 1 but I am not sure how I could go about doing this.
After doing some research, runifdisc
seemed to be the function that looked to obtain the result however, I am unable to get this function run without producing an error.
Error in runifdisc(100) : could not find function "runifdisc"
The image below demonstrates how I am looking to plot the data. I am quite new to R and would appreciate any insight into how I might be able to go about this.
Uniform distribution in disk
double a = random() * 2 * PI
double r = R * sqrt(random())
// Cartesian coordinates
double x = r * cos(a)
double y = r * sin(a)
CodePudding user response:
There's actually no need to rely on a package to do this. It's pretty easy to roll your own function. Here are two possible approaches. The first is crude, but perhaps easier to understand. The second is slightly more sophisticated. Both are based on the tidyverse.
library(tidyverse)
Option 1: Generate points randomly within a square, then filter to retain only those points that lie inside a disc.
runifdisc1 <- function(k, n=2000) {
# Crude approach: need to ensure n is sfficiently larger than k to
# ensure at least k points lie within the unit curcle
tibble(x=runif(n, -1, 1), y=runif(n, -1, 1)) %>%
filter(x*x y*y <= 1) %>%
head(k) %>%
ggplot()
geom_point(aes(x=x, y=y))
coord_fixed(ratio=1)
}
runifdisc1(500)
Option 2: use polar co-ordinates to generate points within the unit disk, then transform to Cartesian co-ordinates.
runifdisc2 <- function(k) {
# More sophisticated approach: polar co-ordinates
tibble(theta=runif(k, -pi, pi), r=runif(k), x=r*cos(theta), y=r*sin(theta))%>%
ggplot()
geom_point(aes(x=x, y=y))
coord_fixed(ratio=1)
}
runifdisc2(500)
There should be a way to plot the polar co ordinates directly, but I don't know what it is. Can anyone advise?
Answering my own question:
runifdisc3 <- function(k) {
tibble(theta=runif(k, -pi, pi), r=runif(k)) %>%
ggplot()
geom_point(aes(x=theta, y=r))
coord_polar("x")
}
runifdisc3(500)