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

使用Altair绘制GeoDataFrame地理数据仅出现蓝色方块问题求助

问题描述

我尝试绘制UHF42 GeoJSON文件的地图,文件地址:
https://github.com/nychealth/coronavirus-data/blob/master/Geography-resources/UHF_resources/UHF42.geo.json
通过GeoPandas加载该文件后,使用matplotlib可以正常绘制出地图,但使用Altair绘制时仅显示蓝色方块。
我尝试使用Altair绘制其他GeoJSON文件可正常出图,也已确认该GeoDataFrame的crs为Altair推荐的WGS 84,暂未定位到问题原因,以下是我的代码:

import pandas as pd
import geopandas as gpd

gdf = gpd.read_file('https://raw.githubusercontent.com/nychealth/coronavirus-data/master/Geography-resources/UHF_resources/UHF42.geo.json')

print(gdf.crs)

# Matplotlib plot
gdf.plot()

# Altair plot
alt.Chart(gdf).mark_geoshape()

解决方法

问题根因:Altair默认使用全局世界地理视图范围,纽约市的地理范围极小,在全局视图下被压缩为小色块,看起来就是蓝色方块,你的CRS配置没有问题。

修正后的可运行代码如下:

import pandas as pd
import geopandas as gpd
import altair as alt

gdf = gpd.read_file('https://raw.githubusercontent.com/nychealth/coronavirus-data/master/Geography-resources/UHF_resources/UHF42.geo.json')

# 确认CRS为WGS84
print(gdf.crs)

# Matplotlib 绘图
gdf.plot()

# Altair 绘图
alt.Chart(gdf).mark_geoshape(
    fill="lightgray",
    stroke="white",
    strokeWidth=0.5
).project(
    type="mercator",
    # 自动适配当前数据集的地理边界,缩放至合适的视图范围
    fit=gdf.total_bounds.tolist()
).properties(
    width=600,
    height=600
)

说明:

  1. 原代码缺少Altair库的导入语句,补充后可避免调用报错
  2. 通过project方法指定投影,同时传入fit参数适配数据集的边界,即可正常显示纽约市的分区地图
  3. 可根据需求调整填充色、描边样式、画布尺寸等参数。

内容的提问来源于stack exchange,提问作者Juan Francisco Saldarriaga

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 12:54:01