Altair中Choropleth(分级统计图)无法显示问题求助
问题原因
你的地图空白核心原因是数据匹配失败:
- 你用
lookup='id'关联topojson数据,但world_110m里的id是国家的ISO 3166-1数字代码(比如法国是250),而你的DataFrame里存的是国家名称字符串,两者完全无法匹配,导致没有数据能映射到地图上,最终显示空白。 - 另外,你DataFrame里的部分国家名称格式和topojson里的标准名称不一致(比如
Turkey (including Gallipoli)、Ireland, Republic of),即使改了lookup字段,也会匹配失败。
修复步骤
1. 修正关联字段
把transform_lookup里的lookup参数改成properties.name——这是world_110m数据里存储国家标准名称的字段,和你的DataFrame字段类型匹配。
2. 统一国家名称格式
清理DataFrame里的国家名称,去掉冗余后缀,和topojson里的标准名称对齐:
- 去掉括号及内部内容(比如
Turkey (including Gallipoli)→Turkey) - 修正非标准名称(比如
Ireland, Republic of→Ireland)
3. 处理无匹配的地区
像Gibraltar这类地区属于国家的海外领地,world_110m是国家级别的地图数据,不会单独显示,这类数据会自动被忽略。
修复后的完整代码
import altair as alt import pandas as pd from vega_datasets import data dat = { 'country': [ 'France', 'Belgium', 'United Kingdom', 'Iraq', 'Turkey (including Gallipoli)', 'Iran', 'Germany', 'Italy', 'India', 'Egypt', 'Greece', 'Malta', 'Ireland, Republic of', 'Pakistan', 'Azerbaijan', 'Switzerland', 'Poland', 'Israel and Palestine (including Gaza)', 'Tanzania', 'Gibraltar', 'Kenya', 'Mozambique', 'Netherlands' ], 'count': [ 7507, 2609, 686, 577, 414, 95, 93, 74, 72, 35, 24, 21, 20, 19, 14, 3, 2, 2, 2, 2, 1, 1, 1 ] } df = pd.DataFrame(dat) # 清理国家名称,匹配topojson的标准名称 df['country'] = df['country'].str.replace(r'\s*\(.*\)', '', regex=True) df.loc[df['country'] == 'Ireland, Republic of', 'country'] = 'Ireland' df.loc[df['country'] == 'Israel and Palestine', 'country'] = 'Israel' # 使用内置世界地图数据 world = alt.topo_feature(data.world_110m.url, 'countries') # 创建分级统计图 choropleth = alt.Chart(world).mark_geoshape( fill='lightgray', stroke='white' ).encode( color=alt.Color('count:Q', scale=alt.Scale(scheme='viridis'), title='死亡人数'), tooltip=[alt.Tooltip('properties.name:N', title='国家'), alt.Tooltip('count:Q', title='死亡人数')] ).transform_lookup( lookup='properties.name', # 改为匹配国家名称字段 from_=alt.LookupData(df, 'country', ['count']) ).properties( title='各国死亡人数统计', width=800, height=500 ).project('equirectangular') choropleth
额外说明
- 如果你需要更精确的地区匹配,可以使用包含更细粒度的地理数据(比如
world_50m),但world_110m已经足够展示国家级别的统计。 - 对于
Israel and Palestine这类合并名称,由于topojson里没有对应条目,这里统一映射为Israel,你可以根据需求调整拆分逻辑。
内容的提问来源于stack exchange,提问作者elksie5000
相关产品推荐
相关产品推荐

