Altair Choropleth Map无法显示问题求助
解决Altair填充地图无法正常显示的问题
你的代码核心问题是国家代码格式不匹配:酒店预订数据中的country字段是ISO 3166-1 alpha-3格式(如PRT、FRA),但vega_datasets提供的世界地图数据world_110m里的id是ISO 3166-1 numeric数字格式(如724、250),两者无法直接匹配,导致地图无法正确关联数据渲染颜色。
修复步骤
- 安装
pycountry库,用于转换国家代码格式 - 将酒店数据中的alpha-3国家代码转换为numeric格式
- 过滤无法识别的国家代码数据
- 修改Altair图表的lookup逻辑,匹配正确的ID字段
修改后的完整代码
import pandas as pd import altair as alt from vega_datasets import data import pycountry # 加载酒店预订数据集 df = pd.read_csv('hotel_bookings.csv') # 计算总客人数,处理缺失值 df['total_guests'] = df['adults'] + df['children'].fillna(0) + df['babies'].fillna(0) # 按国家分组求和 guests_by_country = df.groupby('country')['total_guests'].sum().reset_index() # 转换国家代码为numeric格式 def get_numeric_code(country_code): try: return pycountry.countries.get(alpha_3=country_code).numeric except: return None guests_by_country['country_num'] = guests_by_country['country'].apply(get_numeric_code) # 过滤掉无法转换的国家数据 guests_by_country = guests_by_country.dropna(subset=['country_num']) # 转换为整数类型,匹配地图数据的id类型 guests_by_country['country_num'] = guests_by_country['country_num'].astype(int) # 加载世界地图数据 world_map_data = alt.topo_feature(data.world_110m.url, 'countries') # 创建Altair图表 chart = alt.Chart(world_map_data).mark_geoshape().encode( color=alt.Color('total_guests:Q', scale=alt.Scale(scheme='plasma')), tooltip=[ alt.Tooltip('country:N', title='国家'), alt.Tooltip('total_guests:Q', title='总客人数') ] ).transform_lookup( lookup='id', from_=alt.LookupData( data=guests_by_country, key='country_num', fields=['country', 'total_guests'] ) ).project( type='naturalEarth1' ).properties( title='各国客人分布情况', width=800, height=500 ).configure_view( stroke='black' ).configure_title( fontSize=20 ) # 显示图表 chart
关键修改说明
- 用
pycountry将alpha-3代码转为numeric,确保和地图数据的id字段匹配 - 处理了
children和babies字段的缺失值,避免计算错误 - 在lookup时同时关联
country字段,确保tooltip能显示国家名称 - 增加了图表尺寸配置,让地图显示更清晰
内容的提问来源于stack exchange,提问作者drfqh
相关产品推荐
相关产品推荐

