How to find the Centre of a Polygon in Python

By | February 28, 2015

Finding the centre of of a polygon can be useful for many geomtrical analysis and processing techniques.

This quick guide shows you how to find the centre of a polygon in python.

The Centroid

The centre of a polygon is also known as its centroid. It the arithmetic mean position of all the points that make up the polygon.

How to find the Centre of a Polygon in Python

How to find the centre of a polygon in python

My preferred package for geometry analysis and processing in python is Shapely which happily for us, has a built-in method for finding the centroid of an object.

We can just use:

mypolygon.centroid

This returns a shapely POINT object.

This is all well and good, but in most situations we will want to process this further. So we can do a couple of further things to this centroid.

Firstly we can output it in a more readable way:

mypolygon.centroid.wkt

(‘wkt’ stands for well known text), which outputs:

> 'POINT (3.351351351351351 1.897597597597598)'

Alternatively we can output the centroid as a pair of coordinates:

mypolygon.centroid.coords

(‘wkt’ stands for well known text), which outputs a python list.

> [(3.351351351351351, 1.8975975975975976)]

Which is much more manageable.

python polygons

4 thoughts on “How to find the Centre of a Polygon in Python

  1. Sacha Levy

    hi everyone

    i don’t know if someone has already asked this question but can we set a center to a polygon ?
    i use shapely to plot some polygons (with a list of pooints) and i would like to set a center in order to plot it in another graph

    if anyone has any answer thank you !! that would be very helpful !!

      1. Sacha Levy

        Thank you for your response

        I have a set of coordinates to build a polygon but it’s not a the right place on the graph. So i would like to move it only according to a new centroid.
        i don’t know if i’m clear

        in fact the question is can we move a polygon only by changing its centroid ?

        1. deparkes

          As far as I can tell, I think you would probably need to adjust the coordinates of each of the points individually, by the amount you want to shift the centroid by. The centroid is typically a derived property of the ponits making up the
          polygon, rather than being something that defines the points of the
          polygon.

          Depending on any packages you are using for plotting your polygons, there may be a short cut in how you do this, but behind the scenes I think it will just be doing an offset. You might have some luck looking into Shapely transform: http://toblerity.org/shapely/manual.html#shapely.ops.transform or translate: http://toblerity.org/shapely/manual.html#affine-transformations

Comments are closed.