You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python循环绘制从.shp文件提取的多个多边形

批量绘制SHP文件中的所有多边形

你可以把从SHP文件提取的所有多边形坐标存入一个列表,通过循环遍历列表批量绘制,无需手动逐个调用plt.plot(),具体实现如下:

1. 读取SHP文件并提取多边形坐标(实用方案)

如果还没完成SHP文件的读取,推荐用geopandas库处理,它能便捷提取多边形坐标:

import geopandas as gpd
import matplotlib.pyplot as plt

# 读取目标shp文件
gdf = gpd.read_file("你的文件路径.shp")

# 提取所有多边形的坐标列表,兼容Polygon和MultiPolygon类型
polygons = []
for geom in gdf.geometry:
    if geom.geom_type == "Polygon":
        # 提取单多边形的外边界坐标
        coords = list(geom.exterior.coords)
        polygons.append(coords)
    elif geom.geom_type == "MultiPolygon":
        # 处理由多个子多边形组成的情况
        for sub_poly in geom.geoms:
            coords = list(sub_poly.exterior.coords)
            polygons.append(coords)

2. 循环绘制所有多边形

拿到polygons列表后,直接循环遍历每个多边形,拆分坐标并绘制:

plt.figure(figsize=(10, 10))  # 按需设置画布大小

# 批量绘制所有多边形
for coord in polygons:
    xs, ys = zip(*coord)  # 拆分x、y坐标序列
    plt.plot(xs, ys, linewidth=1, color='darkblue')  # 统一设置线条样式,可按需修改

plt.title("所有多边形分布图")
plt.xlabel("X坐标")
plt.ylabel("Y坐标")
plt.axis('equal')  # 保持坐标比例一致,避免图形变形
plt.show()

如果你已经有了多边形坐标列表

如果已经通过其他方式将所有多边形坐标存入polygons列表(比如你提到的手动收集的列表),直接用以下简化代码即可:

import matplotlib.pyplot as plt

# 假设polygons是你的多边形坐标列表,格式为:[[[x1,y1], [x2,y2], ...], [...], ...]
plt.figure()
for coord in polygons:
    xs, ys = zip(*coord)
    plt.plot(xs, ys)
plt.show()

这样不管有多少个多边形,都能自动批量绘制在同一张图中,无需重复编写绘制代码。

内容的提问来源于stack exchange,提问作者Annelotte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 13:20:31