Skip to content

Instantly share code, notes, and snippets.

@GuangchuangYu
Created April 28, 2012 04:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GuangchuangYu/2515987 to your computer and use it in GitHub Desktop.
Save GuangchuangYu/2515987 to your computer and use it in GitHub Desktop.
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