如果您遇到'Altair: geo_shape doesn't work with selection”错误,这可能是因为Altair中的地理形状类型不支持选择操作。例如,您可能希望通过选择操作改变地图中区域的颜色,但您发现无法实现。
一种解决方法是使用更高级的地图库(例如Folium或Basemap),使用这些库可以在图形中添加交互性。
另一种解决方法是使用基于经纬度坐标的点选取操作来代替区域选择操作。例如,您可以在地图上放置一些固定的点,并使用这些点的坐标进行点选操作。以下是一个示例代码片段:
import altair as alt
from vega_datasets import data
source = data.world_110m.url
points = alt.Chart(source).mark_point().encode(
longitude='longitude:Q',
latitude='latitude:Q',
color=alt.value('gray')
)
click = alt.selection_single(empty='none', fields=['country'])
choropleth = alt.Chart(source).mark_geoshape().encode(
color=alt.condition(click, alt.Color('pop_est:Q', scale=alt.Scale(scheme='greens')), alt.value('lightgray')),
tooltip=[alt.Tooltip('country:N'), alt.Tooltip('pop_est:Q',format=',')]
).transform_lookup(
lookup='id',
from_=alt.LookupData(source, 'id', ['country', 'pop_est'])
).add_selection(
click
)
(choropleth + points).project(
type='naturalEarth1'
).properties(width=650, height=400)
在上面的代码示例中,我们使用marks_point()函数将经纬度坐标转化为点,并使用marks_geoshape()函数将区域转化为具有颜色状态的图形。我们还添加了一个点击事件作为选定区域的条件,并使用transform_lookup()函数将相关数据进行合并。最后,我们将两个图形合并在一起,并使用properties()函数设置地图的大小。