我曾经使用 shapely 制作一个圆圈并将其绘制在之前填充的图上。这曾经工作得很好。最近,我收到索引错误。我把我的代码破坏到了最简单的操作,但它甚至不能做最简单的圆圈。
import descartes
import shapely.geometry as sg
import matplotlib.pyplot as plt
circle = sg.Point((0,0)).buffer(1)
# Plot the cricle
fig = plt.figure()
ax = fig.add_subplot(111)
patch = descartes.PolygonPatch(circle)
ax.add_patch(patch)
plt.show()
以下是我现在遇到的错误。我觉得这可能是新版本与可能发生的事情不匹配。我尝试卸载并重新安装最后一个已知的稳定版本,但这也没有帮助
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Cell In[20], line 6
4 fig = plt.figure()
5 ax = fig.add_subplot(111)
----> 6 patch = descartes.PolygonPatch(circle)
7 ax.add_patch(patch)
8 plt.show()
File ~/env/lib/python3.8/site-packages/descartes/patch.py:87, in PolygonPatch(polygon, **kwargs)
73 def PolygonPatch(polygon, **kwargs):
74 """Constructs a matplotlib patch from a geometric object
75
76 The `polygon` may be a Shapely or GeoJSON-like object with or without holes.
(...)
85
86 """
---> 87 return PathPatch(PolygonPath(polygon), **kwargs)
File ~/env/lib/python3.8/site-packages/descartes/patch.py:62, in PolygonPath(polygon)
58 else:
59 raise ValueError(
60 "A polygon or multi-polygon representation is required")
---> 62 vertices = concatenate([
63 concatenate([asarray(t.exterior)[:, :2]] +
64 [asarray(r)[:, :2] for r in t.interiors])
65 for t in polygon])
66 codes = concatenate([
67 concatenate([coding(t.exterior)] +
68 [coding(r) for r in t.interiors]) for t in polygon])
70 return Path(vertices, codes)
File ~/env/lib/python3.8/site-packages/descartes/patch.py:63, in <listcomp>(.0)
58 else:
59 raise ValueError(
60 "A polygon or multi-polygon representation is required")
62 vertices = concatenate([
---> 63 concatenate([asarray(t.exterior)[:, :2]] +
64 [asarray(r)[:, :2] for r in t.interiors])
65 for t in polygon])
66 codes = concatenate([
67 concatenate([coding(t.exterior)] +
68 [coding(r) for r in t.interiors]) for t in polygon])
70 return Path(vertices, codes)
IndexError: too many indices for array: array is 0-dimensional, but 2 were indexed
因此,据我所知,这个问题来自于
shapely
中 descartes
的错误实现。
我的猜测是
shapely
改变了它处理多边形外部的方式,而 descartes
根本没有更新。
我不知道这是否是最好的主意,但我直接编辑了
descartes
的安装来解决这个问题:
导航到您的
descartes
安装并打开 patch.py
。
在第 62 行你应该看到这段代码:
vertices = concatenate([
concatenate([asarray(t.exterior)[:, :2]] + [asarray(r)[:, :2] for r in t.interiors])
for t in polygon])
只需将
t.exterior
更改为 t.exterior.coords
。希望这可以解决您的问题。
vertices = concatenate([
concatenate([asarray(t.exterior.coords)[:, :2]] + [asarray(r)[:, :2] for r in t.interiors])
for t in polygon])
我正在尝试找到一种方法来向
descartes
开发人员提供此反馈。
我正在测试雅各布给出的答案,但在下一行的
t.interiors
中遇到了类似的错误。我尝试了与他对外部建议的类似修复,将第 64 行更改为 [asarray(r.coords)[:, :2] for r in t.interiors]
但它没有完全起作用(另一个错误刚刚通过包传播)。
最后我不得不将 Shapely 降级到 1.7,这样笛卡尔才能再次工作。所以我的建议是使用它的旧版本,而笛卡尔包没有针对新版本的 Shapely 进行升级。
我相信正确的解决方法是:
vertices = concatenate([
concatenate([asarray(t.exterior.coords)[:, :2]] +
[asarray(r.coords)[:, :2] for r in t.interiors])
for t in polygon])
这适用于 Descartes 1.1.0 和 Shapely 2.0.1