## Introduction

Extracting coordinates from a Shapely polygon in Python is straightforward and can be accomplished by accessing the .coords attribute of the polygon's exterior. Below is a step-by-step guide on how you can do it.

Table of contents

## Create a Polygon using Shapely

First, you need to import the necessary components from Shapely and create a polygon. Here's an example:

`from shapely.geometry import Polygon`

`import numpy as np`

`c1 = np.array((-5.0, -2.5))`

`c2 = np.array((-5.0, 7.5))`

`c3 = np.array((5, 7.5))`

`c4 = np.array((5, -2.5))`

`coords = (c1,c2,c3,c4)`

`myPolygon = Polygon( coords )`

This code snippet creates a simple square as a polygon object.

## Extracting Polygon coordinates

Now, to extract the coordinates from the polygon, specifically from its exterior boundary, you'll use the `.coords`

attribute like so:

`X,Y = myPolygon.exterior.coords.xy`

`print(X)`

`print(Y)`

This code snippet will print:

`array('d', [-5.0, -5.0, 5.0, 5.0, -5.0])`

`array('d', [-2.5, 7.5, 7.5, -2.5, -2.5])`

Please note that the code snippet above returns values of type `array.array`

. To create a list, simply use:

`x_coords = list(X)`

`y_coords = list(Y)`

`print(x_coords)`

`print(y_coords)`

This will create two lists, `x_coords`

and `y_coords`

, that contain the x-coordinates and y-coordinates of the polygon's exterior coordinates:

`[-5.0, -5.0, 5.0, 5.0, -5.0]`

`[-2.5, 7.5, 7.5, -2.5, -2.5]`

This is useful for further processing or plotting the polygon on a graph.

Transform the coordinates of the shape into a list of pairs using the zip function:

`list( zip(x_coords,y_coords) )`

The coordinates are listed in a pair of adjacent x and y values:

`[(-5.0, -2.5), (-5.0, 7.5), (5.0, 7.5), (5.0, -2.5), (-5.0, -2.5)]`

To enhance further processing and manipulation of the polygon coordinates, the list of pairs can be converted into a numpy array using the following code:

`np.asarray( list( zip(x_coords,y_coords) ) )`

The resulting array will display the x and y coordinates accordingly:

`array([[-5. , -2.5],`

`[-5. , 7.5],`

`[ 5. , 7.5],`

`[ 5. , -2.5],`

`[-5. , -2.5]])`

An alternative method involves executing the following code:

`list(myPolygon.exterior.coords)`

This will return a list of tuples, where each tuple contains the X and Y coordinates of a vertex in the exterior boundary:

`[(-5.0, -2.5), (-5.0, 7.5), (5.0, 7.5), (5.0, -2.5), (-5.0, -2.5)]`

This allows us to easily access and manipulate individual coordinates for more advanced applications.

Note: The output includes the starting point at the end as well to signify closure of the polygon. If your polygon has holes, and you wish to extract their coordinates as well, you would iterate over polygon.interiors, applying a similar method to each.

Now that we have successfully extracted the coordinates from a polygon, we can use them for various purposes. For example, we can calculate the area of the polygon using a formula that takes into account the X and Y coordinates.

Another useful application is to plot the polygon on a map using a library such as `matplotlib`

or `folium`

. This allows us to visualize the shape of the polygon and its spatial relationship with other features on the map.

`from matplotlib.pyplot import figure`

`import numpy as np`

`import matplotlib.pyplot as plt`

`import matplotlib.patches as mpatches`

`fig = figure(num=None, figsize=(12, 10), dpi=100, edgecolor='k')`

`ax = plt.axes()`

`poly = mpatches.Polygon(np.stack( (X, Y), axis=1 ),`

`closed=True,`

`ec='k',`

`lw=1,`

`color='coral',`

`alpha=0.5)`

`ax.add_patch(poly)`

`plt.scatter(X,Y)`

`ax.grid(True)`

`ax.spines['left'].set_position('zero')`

`ax.spines['right'].set_color('none')`

`ax.spines['bottom'].set_position('zero')`

`ax.spines['top'].set_color('none')`

`plt.xlim(-10,10)`

`plt.ylim(-10,10)`

`plt.title('How to extract coordinates from a Shapely polygon in python ?')`

`plt.savefig("shapely_extract_polygon_coordinates_01.png", bbox_inches='tight', facecolor='white')`

`plt.show()`

## References

Links | Site |
---|---|

How to create and plot polygons in python using shapely and matplotlib ? | en.moonbooks.org |

shapely user manual: polygons | shapely.readthedocs.io |

conda-forge / packages / shapely | anaconda.org |