I have a scatter plot which I generate using below code
set.seed(10)
mydata <- data.frame(x1 = rnorm(1000), x2 = rnorm(1000))
ind <- replicate(3, sample(nrow(mydata), 500))
head(ind)
feature1 = mydata[ind[,1], "x1"]
feature2 = mydata[ind[,2], "x2"]
# start with a plot
plot(feature1, feature2, pch=4 , col="black")

I want to identify one data point and color it using a different color, which I do using below code
plot(feature1, feature2, pch=4, col=ifelse((feature1 > 2.6 & feature1 < 2.7 ), "red", "black"))

Now, I would like to draw a circle around this point(which is marked in RED) and connect nearest neighboring N points to this point(where N should be a variable)
How can I do it using R?
Here is what I intend to get in my output

Let's first put your data into a matrix p, determine your point of interest p0, and define the number of common neighbours of interest k.
p <- cbind(feature1, feature2)
idx <- p[, 1] > 2.6 & p[, 1] < 2.7
p0 <- p[idx, ]
k <- 10
plot(feature1, feature2, pch = 4, col = ifelse(idx, "red", "black"))
Then we find those k nearest neighbours and draw a circle (using circleFun from this answer) and segments:
kNN <- p[order(colMeans((t(p) - p0)^2))[1 + 1:k], ]
crc <- circleFun(p0, diameter = 2 * sqrt(sum((kNN[k, ] - p0)^2)))
lines(x = crc$x, y = crc$y, col = 'red', lty = 2)
segments(x0 = p0[1], y0 = p0[2], x1 = kNN[, 1], y1 = kNN[, 2], col = "red")

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With