Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot polygon in R

Tags:

r

polygon

I want to plot a polygon from a sample of points (in practice, the polygon is a convex hull) whose coordinates are

x <- c(0.66, 0.26, 0.90, 0.06, 0.94, 0.37)
y <- c(0.99, 0.20, 0.38, 0.77, 0.71, 0.17)

When I apply the polygon function I get the following plot:

plot(x,y,type="n")
polygon(x,y)
text(x,y,1:length(x))

enter image description here

But it is not what I expect... What I want is the following plot:

enter image description here

I obtained this last plot by doing:

good.order <- c(1,5,3,6,2,4)
plot(x,y,type="n")
polygon(x[good.order], y[good.order])
text(x,y,1:length(x))

My question

Basically, my question is: how to obtain the vector of indices (called good order in the code above) which will allow to get the polygon I want?

like image 970
Pop Avatar asked Dec 18 '25 17:12

Pop


2 Answers

Assuming a convex polygon, just take a central point and compute the angle, then order in increasing angle.

> pts = cbind(x,y)
> polygon(pts[order(atan2(x-mean(x),y-mean(y))),])

Note that any cycle of your good.order will work, mine gives:

> order(atan2(x-mean(x),y-mean(y)))
[1] 6 2 4 1 5 3

probably because I've mixed x and y in atan2 and so its thinking about it rotated by 90 degrees, like that matters here.

like image 129
Spacedman Avatar answered Dec 20 '25 08:12

Spacedman


Here is one possibility. The idea is to use the angle around the center for ordering:

x <- c(0.66, 0.26, 0.90, 0.06, 0.94, 0.37)
y <- c(0.99, 0.20, 0.38, 0.77, 0.71, 0.17)

xnew <- x[order(Arg(scale(x) + scale(y) * 1i))]
ynew <- y[order(Arg(scale(x) + scale(y) * 1i))]

plot(xnew, ynew, type = "n")
polygon(xnew ,ynew)
text(x, y, 1:length(x))

resulting plot

like image 21
Roland Avatar answered Dec 20 '25 06:12

Roland



Donate For Us

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