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

Python绘制Polygon:CSV文件存储格式及绘图实现技术问询

关于Polygon经纬度存储与Python绘制的解决方案

1. CSV中存储Polygon经纬度数据的两种常用方式

方式一:单记录字符串存储(适合简单场景)

将单个Polygon的所有坐标点拼接成一个字符串,用分号分隔不同点,逗号分隔经纬度,同时每行保留Polygon的名称、人口等属性信息。示例CSV内容:

polygon_name,population,coordinates
北京天安门区域,1000,"116.397,39.908;116.407,39.908;116.407,39.918;116.397,39.918"
上海外滩区域,2500,"121.491,31.234;121.499,31.234;121.499,31.242;121.491,31.242"

方式二:多记录关联存储(适合复杂Polygon)

每个Polygon的每个坐标点占一行,用唯一的polygon_id关联同一Polygon的所有点,每行重复存储名称、人口等属性(单CSV场景下重复存储更易直接处理)。示例CSV内容:

polygon_id,polygon_name,population,longitude,latitude
1,北京天安门区域,1000,116.397,39.908
1,北京天安门区域,1000,116.407,39.908
1,北京天安门区域,1000,116.407,39.918
1,北京天安门区域,1000,116.397,39.918
2,上海外滩区域,2500,121.491,31.234
2,上海外滩区域,2500,121.499,31.234
2,上海外滩区域,2500,121.499,31.242
2,上海外滩区域,2500,121.491,31.242

2. Python读取CSV并绘制Polygon的代码示例

首先安装依赖库:

pip install pandas matplotlib shapely descartes

对应方式一的代码(单记录CSV)

import pandas as pd
import matplotlib.pyplot as plt
from shapely.geometry import Polygon
from descartes import PolygonPatch

# 读取CSV文件
df = pd.read_csv('polygons.csv')

# 创建绘图对象
fig, ax = plt.subplots(figsize=(10, 8))

# 遍历每条Polygon记录
for _, row in df.iterrows():
    # 解析坐标字符串为经纬度元组列表
    coord_pairs = row['coordinates'].split(';')
    coords = [tuple(map(float, pair.split(','))) for pair in coord_pairs]
    # 构建Polygon几何对象
    polygon = Polygon(coords)
    # 生成多边形补丁并添加到图中
    patch = PolygonPatch(polygon, alpha=0.5, label=f"{row['polygon_name']} (人口:{row['population']})")
    ax.add_patch(patch)
    # 在多边形中心标注名称
    centroid = polygon.centroid
    ax.text(centroid.x, centroid.y, row['polygon_name'], fontsize=10, ha='center')

# 设置图表属性
ax.set_xlabel('经度')
ax.set_ylabel('纬度')
ax.set_title('区域Polygon分布')
ax.legend()
ax.set_aspect('equal')  # 保证经纬度比例正确
plt.show()

对应方式二的代码(多记录CSV)

import pandas as pd
import matplotlib.pyplot as plt
from shapely.geometry import Polygon
from descartes import PolygonPatch

# 读取CSV文件
df = pd.read_csv('polygons_multi.csv')

# 创建绘图对象
fig, ax = plt.subplots(figsize=(10, 8))

# 按polygon_id分组处理每个Polygon
for _, group in df.groupby('polygon_id'):
    # 提取当前Polygon的坐标
    coords = list(zip(group['longitude'], group['latitude']))
    polygon = Polygon(coords)
    # 获取属性信息(取分组内第一条即可)
    name = group['polygon_name'].iloc[0]
    population = group['population'].iloc[0]
    # 添加多边形到图中
    patch = PolygonPatch(polygon, alpha=0.5, label=f"{name} (人口:{population})")
    ax.add_patch(patch)
    # 标注名称
    centroid = polygon.centroid
    ax.text(centroid.x, centroid.y, name, fontsize=10, ha='center')

# 设置图表属性
ax.set_xlabel('经度')
ax.set_ylabel('纬度')
ax.set_title('区域Polygon分布')
ax.legend()
ax.set_aspect('equal')
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 20:06:22