Descartes库PolygonPatch报错IndexError:数组索引过多问题求助
解决Descartes与Shapely 2.0+兼容的IndexError问题
问题根源
Descartes包已多年未更新,完全不兼容Shapely 2.0及以上版本。Shapely 2.0重构了内部几何对象的结构,比如Polygon.interiors返回的LinearRing对象,直接用np.asarray()转换会得到0维数组,而Descartes的旧代码尝试用二维索引[:, :2]访问,触发IndexError。
解决方案
方案1:降级Shapely到1.x版本
直接安装Shapely 1.x系列版本,匹配Descartes的兼容要求:
pip install shapely<2.0 --force-reinstall
安装完成后,PyPI上的Descartes示例代码即可正常运行。
方案2:替换Descartes为Shapely自带绘图模块
Shapely 2.0原生提供了shapely.plotting模块,无需依赖Descartes。以你示例中的buffer生成的多边形为例,修改代码如下:
原Descartes代码片段:
from descartes import PolygonPatch dilated = line.buffer(0.5) patch1 = PolygonPatch(dilated, fc=BLUE, ec=BLUE, alpha=0.5, zorder=2) ax.add_patch(patch1)
替换为Shapely原生代码:
from shapely.plotting import plot_polygon dilated = line.buffer(0.5) plot_polygon(dilated, ax=ax, facecolor=BLUE, edgecolor=BLUE, alpha=0.5, zorder=2)
如果需要更精细控制路径样式,也可以手动构建matplotlib.path.Path对象,参考Shapely官方文档的绘图示例。
方案3:修改Descartes源码临时适配
如果必须保留Shapely 2.0,可手动修改Descartes的patch.py文件:
找到~/.local/lib/python3.8/site-packages/descartes/patch.py中第64行:
[asarray(r)[:, :2] for r in t.interiors]
修改为:
[asarray(r.coords)[:, :2] for r in t.interiors]
同时确保第63行的asarray(t.exterior.coords)保持不变。但此方法仅为临时补丁,后续Descartes无更新的话,重新安装包会失效。
内容的提问来源于stack exchange,提问作者user252935
相关产品推荐
相关产品推荐

