Turfjs / turf

A modular geospatial engine written in JavaScript and TypeScript

Home Page:https://turfjs.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

centroid vs mean centre

jamaps opened this issue · comments

Greetings turf people,

I think turf's centroid method doesn't actually calculate the true centroid of a polygon. It seems to calculate the mean of all the vertices of a polygon rather than the mean of all the points that fall within the polygon. Thus, if there are lots of vertices on one side of the shape, it pulls the centroid point towards that edge.

Centroid calculated by turf:
image

Centroid calculated in QGIS (using "polygon centroids" under geometry tools)
image

I think what turf is calculating is actually the mean centre, which can be quite useful for cluster analysis, but it's not the same as the centroid of a polygon. (https://www.wikiwand.com/en/Centroid)

Maybe this is just semantics, but I found the output of turf's centroid function confusing as I expected one result and received another.

All the best,

Just checking this myself and was about to ask the same question, the doc says " calculates the centroid using the arithmetic mean of all vertices" which is what the function is doing, qgis I believe is calculating the weighted mean. Have you tried postgis but apparently it would give the same answer as turf for centroid. I think adding the weighted option as a switch/parameter would be nice instead of having to add the module https://github.com/Turfjs/turf-weighted-centroid maybe check with that module see if its similar to Qgis

The turf-weighted-centroid module implements an algorithm that weights the centroid of a collection of features by some external heuristic (ie: population, median income, etc.).

I think what turf is calculating is actually the mean centre, which can be quite useful for cluster analysis, but it's not the same as the centroid of a polygon.

There are many different centroid algorithms that are used in different analysis contexts. I would be open to a module that implements the desired behavior here, provided a generic, concrete algorithm to follow (the same goes for other types of centroid algorithms). I'm going to close this ticket, but feel free to open another one with a reference to a specific algorithm that is needed.

Same issue here - can't figure out how to achieve QGIS-like centroids with Turf. turf-weighted-centroid seems to be solving a different problem.

Have you found the solution @jamaps?

UPD: center or pointOnSurface provide slightly better results than centroid, but this is still not the weighted center of a polygon.

@kachkaev I would give @mourner's new Polylabel module a spin.

Polylabel implements a fast centroid algorithm (modified pole of inaccessibility) aimed at visual rendering (unlike any of the turf centroid algorithms, which have different design goals).