[R] placing labels in polygon center ?
Barry Rowlingson
B.Rowlingson at lancaster.ac.uk
Wed Aug 13 13:32:18 CEST 2003
> Trying to recall from my physics education, the mass centre is at the
> averages of the coordinates of the corners, isn't it?
Perhaps for simple polygons it is... One thing it certainly isnt is
the average of all the coordinates (a mistake I have seen geographers
make!).
Here's some code derived from the java source code here:
http://astronomy.swin.edu.au/~pbourke/geometry/polyarea/
You also get a PolygonArea function for free. Feed it a two-column
matrix of X and Y coords. Out comes a vector of (x,y) for the centroid.
PolygonArea <- function(polygon)
{
N <- dim(polygon)[1]
area = 0;
for (i in 1:N) {
j = 1+(i %% N)
area = area + polygon[i,1] * polygon[j,2]
area = area - polygon[i,2] * polygon[j,1]
}
area =area/2.0;
return(abs(area))
}
PolygonCenterOfMass <- function(polygon)
{
N <- dim(polygon)[1]
cx=0 ; cy=0
A=PolygonArea(polygon);
factor=0;
for (i in 1:N) {
j = (i %% N)+1
factor=(polygon[i,1]*polygon[j,2]-polygon[j,1]*polygon[i,2])
cx=cx+(polygon[i,1]+polygon[j,1])*factor
cy=cy+(polygon[i,2]+polygon[j,2])*factor
}
A=A*6.0
factor=1/A
cx=cx*factor
cy=cy*factor
return(c(cx,cy))
}
Something like this will end up in my Rmap library......
Baz
More information about the R-help
mailing list