我有一个跨越各种多边形的线串,存储为GeoJsons。我想将线分成每个多边形区域内的各个部分。但是,我还无法实现这一目标。这是到目前为止我可以重现的示例:
from shapely.geometry import Point, LineString, Polygon
from shapely.ops import split
from matplotlib import pyplot as plt
poly = {
'type': "Feature",
'geometry': {
"type": "Polygon",
"coordinates": ([(2,2),(2,4),(4,4),(4,2)]),
},
'properties': {
'id': 'A'
}
}
line = {
'type': "Feature",
'geometry': {
"type": "Linestring",
"coordinates": ([(3,3),(5,1)]),
},
'properties': {
'id': 'A'
}
}
poly = Polygon(poly['geometry']['coordinates'])
line = LineString(line['geometry']['coordinates'])
x,y = poly.exterior.xy
x2,y2 = line.coords
plt.plot(x, y, x2, y2)
plt.show()
然后我尝试通过多边形分割线,如下所示:
new_lines = split(line, poly)
但是我得到以下输出,看起来似乎不正确:
GEOMETRYCOLLECTION (LINESTRING (3 3, 4 2), LINESTRING (4 2, 5 1))
我期望有3条线,其中1条存在于方形多边形内,然后2条分别存在于多边形外。
答案 0 :(得分:0)
似乎split可以按预期工作,但是线的坐标以一种误导性的方式绘制-应该像多边形一样使用def farey(n):
return (n*(n+3))//2 - sum(farey(n//k) for k in range(2, n+1))
来获得线.xy
和xs
:
ys
from shapely.geometry import Point, LineString, Polygon
from shapely.ops import split
from matplotlib import pyplot as plt
poly = Polygon([(2,2),(2,4),(4,4),(4,2)])
original_line = LineString([(3,3),(5,1)])
line = LineString([(3,1), (3,5)])
x, y = poly.exterior.xy
x2, y2 = line.xy
x3, y3 = original_line.xy
plt.plot(x, y, x2, y2)
plt.show()
plt.plot(x, y, x3, y3)
plt.show()