# [R] ordering points as vertex of a polygon

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon Jun 14 12:31:15 CEST 2004

```On Mon, 14 Jun 2004, Luca Scrucca wrote:

> Dear R-users,
>
> Suppose I have the following x-y coordinates which give the boundaries of
> a polygon:
> > x <- c(5,4,5,9,6,6,4,7,10,7,10,4,10)
> > y <- c(6,3,2,6,3,7,5,4,4,7, 5,4, 6)
>
> I would like to plot the following graph:
> > plot(x,y)
> > ord <- c(7,12,2,3,5,8,9,11,13,4,10,6,1)
> > polygon(x[ord],y[ord])
>
> How I can obtain the above ordering (in the example an anti-clockwise
> ordering) such that I can use polygon() to connect the points?

What exactly is the ordering?  The polygon is not convex, so the ordering
depends on where you measure angles from.  Generally though you could try
something like.

xy <- cbind(x,y)
angM <- xy - rep(c(7,5), each=length(x))
angs <- apply(angM, 1, function(x) atan2(x, x))
ord <- sort.list(angs)

which seems to replicate your solution.

> I searched previous messages but I did not find any relevant to this
> problem.

It is not really an R question.

--
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

```