Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
get points within a circle
set.seed(123)
x <- rnorm(100)
y <- rnorm(100)
points.df <- data.frame(x=x,y=y)
center <- c(0.2, 0.3)
diameter <- 2
d <- apply(points.df, 1, function(x) x-center)
d <- t(d^2)
idx <- apply(d, 1, sum) < (diameter/2)^2
## points.df[idx,] is the subset of points which locate within the circle.
points.df <- data.frame(points.df, inCircle=factor(idx, levels=c("TRUE", "FALSE")))
require(ggplot2)
p <- ggplot(points.df, aes(x,y))+geom_point(aes(color=inCircle))
circleFun <- function(center = c(0,0),diameter = 1, npoints = 100){
r = diameter / 2
tt <- seq(0,2*pi,length.out = npoints)
xx <- center[1] + r * cos(tt)
yy <- center[2] + r * sin(tt)
return(data.frame(x = xx, y = yy))
}
circle.df <- circleFun(center, diameter)
p+geom_path(data=circle.df, aes(x,y))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.