Skip to content Skip to sidebar Skip to footer

Gcentroid (rgeos) R Vs. Actual Centroid (in Python)

Summary: I thought that using gCentroid in R would return the centroid of a group of points, however I realised that for some reason it actually returns the geometric mean and not

Solution 1:

It turns out that: if a group of 'Points' are supplied, then instead of guessing a polygon through the points or producing a convex hull - the command automatically gives you the mean of the projected co-ordinates.

However, if you supply a polygon then you get a centroid (the same as the python script) - in my python example I was missing one co-ordinate:

centroid = get_polygon_centroid(np.array([[-6424797.94257892,  7164920.56353916],
                                             [-5582828.69570672,  6739129.64644454],
                                             [-5583459.32266293,  6808624.95123077],
                                             [-5855637.16642608, 7316808.01148585],
                                             [-5941009.53089084,  7067939.71641507],
                                             [-6424797.94257892, 7164920.56353916]]))
#polygon closed
#[-5875317.844022617010915.37286505]

So running this R-script:

x = readWKT(paste("POLYGON((-6424797.94257892  7164920.56353916,
                  -5582828.69570672  6739129.64644454,
                  -5583459.32266293  6808624.95123077,
                  -5855637.16642608  7316808.01148585,
                  -5941009.53089084  7067939.71641507,
                  -6424797.94257892  7164920.56353916))"))

python_cent = readWKT(paste("POINT(-5875317.84402261  7010915.37286505)"))
r_cent = gCentroid(x) 

plot(x)
plot(r_cent,add=T,col='red', pch = 0)
plot(python_cent, add=T,col='green', pch = 1)

Everything matches nicely:

enter image description here

I added a bit more info on my blog if interested.

Post a Comment for "Gcentroid (rgeos) R Vs. Actual Centroid (in Python)"