Python绘制英国地理Shapefile异常:点序问题还是方法错误?
解决Shapefile绘制边界时的点关联混乱问题
嘿,我来帮你搞定这个边界绘制混乱的问题!你遇到的情况不是单纯的点序问题,而是对Shapefile的结构理解不到位导致的处理方法有误。
问题根源
Shapefile里的多边形要素经常包含多个独立部分(比如英国的主岛和周边小岛、飞地),这些部分的顶点都存在shape.points列表里,但它们是通过shape.parts属性来区分的——parts里存储的是每个独立部分在points列表中的起始索引。你的代码直接把所有顶点当成一条连续的线来绘制,自然会出现跨区域的错误连线,把不同岛屿/区域的点乱连在一起。
修正后的代码
只需要在处理每个shape的时候,按照parts的索引分割顶点,单独绘制每个部分就行:
import matplotlib.pyplot as plt import shapefile ukmap = shapefile.Reader("./Archive/UK_map.shp") txt_shapes = [] for ukmapshape in ukmap.shapes(): # 获取各部分起始索引,最后添加总点数作为结束标记 parts = ukmapshape.parts + [len(ukmapshape.points)] # 遍历每个独立部分,提取对应顶点 for start_idx, end_idx in zip(parts[:-1], parts[1:]): part_points = ukmapshape.points[start_idx:end_idx] listx = [x for x, y in part_points] listy = [y for x, y in part_points] txt_shapes.append([listx, listy]) # 逐个绘制每个独立区域 for zone in txt_shapes: x, y = zone plt.plot(x, y) plt.axis('equal') plt.show()
额外建议
如果之后能解决Fiona/GDAL的安装问题,推荐使用geopandas这类更易用的GIS库,读取并绘制Shapefile只需要几行代码:
import geopandas as gpd uk_map = gpd.read_file("./Archive/UK_map.shp") uk_map.plot() plt.show()
它会自动处理Shapefile的复杂结构,省去手动分割部分的麻烦。
内容的提问来源于stack exchange,提问作者CromeX
相关产品推荐
相关产品推荐

