Altair绘制森林砍伐世界地图时换行调用transform_lookup报错
语法错误原因与修复
你的代码报错是因为链式调用断裂:你把.transform_lookup()单独放在了变量赋值语句之外,Python无法识别这个方法属于哪个Chart对象。
修复步骤
- 把
transform_lookup整合到Chart的链式调用中,确保它紧跟在前面的方法(比如.project())之后,不要单独换行成新的语句。 - 修正lookup字段:topojson世界地图数据里的国家名称字段是
properties.name,需要和你数据集里的Entity字段匹配,否则无法正确关联数据。
修正后的完整代码
world_map = alt.topo_feature(data.world_110m.url, 'countries') chart = alt.Chart(world_map).mark_geoshape().encode( color=alt.Color('Annual net change in forest area:Q'), tooltip=[ alt.Tooltip('properties.name:N', title='Country'), alt.Tooltip('properties.pop_est:Q', title='Population'), alt.Tooltip('Annual net change in forest area:Q', title='Forest Area Net Change') ] ).properties( width=600, height=400 ).project('naturalEarth1').transform_lookup( lookup="properties.name", from_=alt.LookupData(Forest, 'Entity', ['Annual net change in forest area']) ) chart.display()
额外说明
- 链式调用时,每个方法调用都要直接连接在前一个方法的末尾,也可以用括号包裹整个链式结构保持格式清晰,但不能在赋值完成后再单独调用方法。
- 确保Forest数据集里的
Entity字段和topojson中的properties.name字段内容完全匹配(比如国家名称的拼写、大小写一致),否则会出现数据关联失败的情况。
内容的提问来源于stack exchange,提问作者Schmarti
相关产品推荐
相关产品推荐

