Introduction
In this article, we will explore how to plot polygons in python using shapely library. Shapely is a python package for computational geometry which provides easy access to geometric objects such as points, lines, and polygons. Using shapely, we can create and manipulate geometric objects in python and visualize them using various plotting tools.
Before jumping into the details of plotting polygons with shapely, let's first understand some basic concepts. In geometry, a polygon is a closed shape formed by connecting points together with straight lines. It can have three or more sides and each point where two line segments meet is called a vertex. Some common examples of polygons are triangles, squares, rectangles, and pentagons. Polygons can be simple or complex depending on the number of sides and vertices they have. In python, we can represent polygons using coordinates of their vertices.
Create and plot a square using python
To create a polygon in Shapely, we need to provide a list of coordinates representing the exterior ring of the polygon.
Creating a square
Let's create a simple square with coordinates (0, 0), (0, a), (a, a), and (a, 0) using Shapely:
from shapely.geometry import Polygon
import numpy as np
a = 2.0 # square size
pos = np.array((1.0, 2.0))
c1 = np.array((0.0, 0.0)) + pos
c2 = np.array((0.0, a)) + pos
c3 = np.array((a, a)) + pos
c4 = np.array((a, 0.0)) + pos
coords = (c1,c2,c3,c4)
square = Polygon( coords )
Please note that once you have created a polygon using shapely, you can easily retrieve the coordinates.
To retrieve the coordinates for a polygon created using shapely, you can use the exterior.coords
method. This will return a list of tuples representing the coordinates of each vertex in the polygon. You can then use these coordinates to plot your polygon on a graph or map.
X,Y = square.exterior.coords.xy
print(np.array(X))
print(np.array(Y))
the code above will return:
[1. 1. 3. 3. 1.]
[2. 4. 4. 2. 2.]
Note that we can the stack X and Y in a 2D array of dimension (5,1)
np.stack( (X, Y), axis=1 )
returns
array([[1., 2.],
[1., 4.],
[3., 4.],
[3., 2.],
[1., 2.]])
Plotting a square
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.xlim(0,6)
plt.ylim(0,6)
plt.title('How to create and plot a square in python using shapely and matplotlib ?')
plt.savefig("shapely_square.png", bbox_inches='tight', facecolor='white')
plt.show()
Another example
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)
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(-6,6)
plt.ylim(-6,6)
plt.title('How to create and plot a square in python using shapely and matplotlib ?')
plt.savefig("shapely_square_02.png", bbox_inches='tight', facecolor='white')
plt.show()
Create and plot a rectangle using python
To create a rectangle, we need to provide the coordinates of its four corners. In Shapely, polygons are defined using tuples of (x,y) coordinates. Let's define our coordinates:
Creating a rectangle
from shapely.geometry import Polygon
import numpy as np
a = 2.0 # rectangle size
b = 4.0 # rectangle size
pos = np.array((1.0, 2.0))
c1 = np.array((0.0, 0.0)) + pos
c2 = np.array((0.0, a)) + pos
c3 = np.array((b, a)) + pos
c4 = np.array((b, 0.0)) + pos
coords = (c1,c2,c3,c4)
rect = Polygon( coords )
rect.exterior.coords.xy
X,Y = rect.exterior.coords.xy
Plotting a rectangle
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.xlim(0,6)
plt.ylim(0,6)
plt.title('How to create and plot a rectangle in python using shapely and matplotlib ?')
plt.savefig("shapely_rectangle.png", bbox_inches='tight', facecolor='white')
plt.show()
Create and plot a triangle using python
To create a triangle, we need to provide the coordinates of its four corners. In Shapely, polygons are defined using tuples of (x,y) coordinates. Let's define our coordinates:
Creating a triangle
from shapely.geometry import Polygon
import numpy as np
a = 2.0 # rectangle size
b = 4.0 # rectangle size
pos = np.array((1.0, 2.0))
c1 = np.array((0.0, 0.0)) + pos
c2 = np.array((0.0, a)) + pos
c3 = np.array((b, a)) + pos
c4 = np.array((b, 0.0)) + pos
coords = (c1,c2,c3,c4)
triangle = Polygon( coords )
triangle.exterior.coords.xy
X,Y = triangle.exterior.coords.xy
Plotting a triangle
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.xlim(0,6)
plt.ylim(0,6)
plt.title('How to create and plot a triangle in python using shapely and matplotlib ?')
plt.savefig("shapely_triangle.png", bbox_inches='tight', facecolor='white')
plt.show()
References
Links | Site |
---|---|
matplotlib.patches.Polygon | matplotlib.org |
numpy.stack | numpy.org |
How to put the origin in the center of the figure with matplotlib ? | moonbooks.org |
How to plot a circle in python using matplotlib ? | moonbooks.org |