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

解决Geopandas与Altair中地图倒置及投影问题

伦敦多层地图绘制问题解答

一、Geopandas绘图报错ValueError: aspect must be finite and positive

原因

你的GeoDataFrame使用的是EPSG:4326(WGS84经纬度坐标系),这种地理坐标系的单位是度,Geopandas默认会根据数据的经纬度范围计算绘图宽高比,但伦敦的经纬度范围导致自动计算的aspect值出现异常(非有限正数)。

解决方案

你用aspect=1强制固定宽高比是临时解决方法,更合理的方式是转换为英国本土的投影坐标系EPSG:27700(OSGB36国家网格),该坐标系以米为单位,能自动计算正确的宽高比:

london_wards_gpd = london_wards_gpd.to_crs(epsg=27700)
london_wards_gpd.plot()  # 无需手动设置aspect

二、Altair图层叠加后地图倒置

核心原因

你使用了type='identity'投影,该投影会直接使用原始坐标值渲染图像,但:

  • EPSG:4326坐标系中,纬度值越大越靠北(比如伦敦纬度约51.5°N);
  • 图像渲染的坐标系中,y轴坐标值越大越靠下;
    两者的y轴方向相反,导致地图上下倒置。

三种修复方案

方案1:修改投影参数,翻转Y轴

在project中添加reflectY=True,直接翻转y轴方向:

london_wards_map = alt.Chart(london_wards_gpd).mark_geoshape(
    fill=None,
    stroke='darkgray',
    strokeWidth=1
).encode(
    tooltip='NAME:N'
).properties(
    width=800,
    height=600
).project(
    type='identity',
    reflectY=True  # 新增:翻转Y轴
)

hackney_layer = alt.Chart(hackney_wards).mark_geoshape(
    fill='lightgray',
    stroke='darkgray',
    strokeWidth=1
).encode(
    tooltip='NAME:N'
).properties(
    width=800,
    height=600
).project(
    type='identity',
    reflectY=True  # 同样添加该参数
)

方案2:使用适配英国的投影类型

替换identity为适合英国的投影(如mercator或指定EPSG:27700),Altair会自动处理坐标方向:

.project(
    type='mercator'
)
# 或者指定EPSG投影
.project(
    type='EPSG27700'
)

方案3:提前转换GeoDataFrame到EPSG:27700

将数据转换为英国本土投影坐标系后,identity投影的y轴方向与图像坐标系一致,不会倒置:

# 转换CRS
london_wards_gpd = london_wards_gpd.to_crs(epsg=27700)
hackney_wards = london_wards_gpd[london_wards_gpd['DISTRICT']=='Hackney']

# 后续Altair代码无需修改投影参数,直接用identity即可
london_wards_map = alt.Chart(london_wards_gpd).mark_geoshape(...).project(type='identity')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 22:07:43