Search code examples
pythonshapelyset-difference

How to use Shapely for subtracting two polygons


I am not really sure how to explain this but I have 2 polygons, Polygon1 and Polygon2. These polygons overlapped with each other. How to do I get Polygon2 using Shapely without the P from Polygon1.


Solution

  • You are looking for a difference. In Shapely you can calculate it either by using a difference method or by simply subtracting* one polygon from another:

    from shapely.geometry import Polygon
    
    polygon1 = Polygon([(0.5, -0.866025), (1, 0), (0.5, 0.866025), (-0.5, 0.866025), (-1, 0), (-0.5, -0.866025)])
    polygon2 = Polygon([(1, -0.866025), (1.866025, 0), (1, 0.866025), (0.133975, 0)])
    

    enter image description here

    difference = polygon2.difference(polygon1)  # or difference = polygon2 - polygon1
    

    enter image description here

    See docs for more set-theoretic methods.


    *This feature is not documented. See issue on GitHub: Document set-like properties.