Cut a polygon with two lines in Shapely

Yuxiang Wang picture Yuxiang Wang · Sep 6, 2016 · Viewed 8.7k times · Source

I am trying to cut a shapely.geometry.Polygon instance in two parts with two lines. For example, in the code below, polygon is a ring and if we cut it with line1 and line2 we should get two partial rings, one w/ 270 degrees and one with 90 degrees. Would there be a clean way to do this?

from shapely.geometry import Point, LineString, Polygon

polygon = Point(0, 0).buffer(2).difference(Point(0, 0).buffer(1))
line1 = LineString([(0, 0), (3, 3)])
line2 = LineString([(0, 0), (3, -3)])

Answer

Yuxiang Wang picture Yuxiang Wang · Sep 6, 2016

Ken Watford answered here about using buffer and difference to do the trick, w/ the drawback of losing a bit of the area. An example code below:

from shapely.geometry import Point, LineString, Polygon

polygon = Point(0, 0).buffer(2).difference(Point(0, 0).buffer(1))
line1 = LineString([(0, 0), (3, 3)])
line2 = LineString([(0, 0), (3, -3)])

line1_pol = line1.buffer(1e-3)
line2_pol = line2.buffer(1e-3)

new_polygon = polygon.difference(line1_pol).difference(line2_pol)

Works for now, and I'd be interested to see whether there is another (potentially w/o losing area) method!