Snapping#

import geopandas as gpd
import geoplanar
from shapely.geometry import Polygon

Snaps polygon edges to each another if the distance between polygon edges is below a threshold value

p1 = Polygon([[0, 0], [10,0], [10,10], [0,10]])
p2 = Polygon([(10.4, 0), (21,0), (21,20), (10.4,20)])
gdf = gpd.GeoDataFrame(geometry=[p1, p2])
gdf.plot(edgecolor='k')
<Axes: >
_images/3e4cde80f3d755d87c12d4065ace84ee79f1c80954c0951e181228d622527c00.png
# default threshold is 0.5, so these two polygons will be snapped together
gdf1 = geoplanar.snap(gdf)
gdf1.plot(edgecolor='k')
<Axes: >
_images/d564c6d3a66ee65bcacc6a85c22bde9b678dd8c2c96757154f144b81fa52e1d3.png
# at a threshold of 0.4 or less, polygons are not snapped together because the distance between segmentized vertices on the
# two polygons is larger than 0.4.
# threshold should be ~10% larger than the distance between the two polygon edges to ensure snapping
gdf2 = geoplanar.snap(gdf, threshold=0.4)
gdf2.plot(edgecolor='k')
<Axes: >
_images/3e4cde80f3d755d87c12d4065ace84ee79f1c80954c0951e181228d622527c00.png

Irregular shape#

p3 = Polygon( [[0, 0], [10,0], [13,13], [3,10] ] )
p4 = Polygon( [(10.7, 2), (23,10), (15,20)] )
gdf4=gpd.GeoDataFrame(geometry=[p3,p4])
gdf4.plot(edgecolor='k')
<Axes: >
_images/4c90c3e051594520a709322b03ef7db89b873791ff2c2d475b7da421f0c019bf.png
# default threshold is 0.5
gdf5 = geoplanar.snap(gdf4)
gdf5.plot(edgecolor='k')
<Axes: >
_images/66d53e283de2743d4cdaeedd85f4325c32eb80acce9cd6d571ce88b2ab068d9f.png
gdf5.area
0    113.62863
1     93.50000
dtype: float64
# only the sections of edges that are within the threshold distance of each other will be snapped together
gdf6 = geoplanar.snap(gdf4, threshold=0.3)
gdf6.plot(edgecolor='k')
<Axes: >
_images/d50da70e6f1763b077bab3480c97ed8051c14bdfdac99ea5bfc4ce94cc22ce8f.png

Multiple shapes#

p5 = Polygon( [[0, 0], [10,0], [13,13], [3,10] ] )
p6 = Polygon( [(10.7, 2), (23,10), (15,20)] )
p7 = Polygon( [(10.7, 1.5), (23,9), (10.3,0)] )
gdf7=gpd.GeoDataFrame(geometry=[p5,p6,p7])
gdf7.plot(edgecolor='k')
<Axes: >
_images/bd9760739a69430a79dde42bab40960f65829dbc41300f2e23868eb3772d256b.png
gdf8 = geoplanar.snap(gdf7,threshold = 1)
gdf8.plot(edgecolor='k')
<Axes: >
_images/877a53637a086fd13890ed12a5e1a72d4f5a5e371685decb152ff481381da14e.png
gdf8.area
0    114.114683
1    102.327758
2      7.725000
dtype: float64

Snapping may result in holes if multiple polygons are snapped to one another. This is because polygons are only snapped to one other polygon at a time, and are not optimally fitted to multiple polygons simultaneously. Further treatment can resolve this issue, such as fill_gaps().