Altair:geo_shape 不适用于选择

问题描述

我正在制作一个 Choropleth 地图,该地图将显示不同州之间的相似性。因此,当您从下拉列表中选择一个州时,地图将显示它与其他州的相似度。

为此,我使用了 2 个数据集:

  • DatasetA:长格式数据框,包含 3 列:状态 1、状态 2 以及它们之间的相似性。
  • DatasetB:包含每个州的几何形状的 GeoDataFrame。

当我尝试在没有选择的情况下绘制此图时,它会起作用:

alt.Chart(gdf).mark_geoshape(
).encode(
    color='Similarity:O',tooltip = ['Similarity:Q']
).properties(
    projection={'type': 'albersUsa'},width=700,height=400
).transform_lookup(
    lookup='State',from_=alt.LookupData(source,'State',source.columns.values)
)

但是一旦我添加了选择,那么它只在我选择怀俄明州(数据集 A 中的最后一个州)时才有效。当我选择其他州时,情节消失。

input_dropdown = alt.binding_select(options=source.State.unique())
selection = alt.selection_single(fields=['Similarity_to'],bind=input_dropdown,init={'Similarity_to': 'New York'})

alt.Chart(gdf).mark_geoshape(
).encode(
    color='Similarity:Q',source.columns.values)
).transform_filter(
    selection
).add_selection(
    selection
)

这是一个演示它的剪辑:https://www.loom.com/share/292e8b1a80344cf5a998a54f453ece2c

解决方法

我通过使用 transform_fold 来实现这一点。问题是 transform_lookup 只匹配一次,所以如果数据集中有多个匹配项,它会忽略它们。因此,您必须使用宽格式数据集,然后使用 transform_fold 将其转换回长格式。

input_dropdown = alt.binding_select(options=source.State.unique())
selection = alt.selection_single(fields=['Similarity_to'],bind=input_dropdown,init={'Similarity_to': 'New York'})

alt.Chart(gdf).mark_geoshape(
   stroke='black'
).encode(
   color='Similarity:Q',tooltip = ['Similarity:Q']
).properties(
   projection={'type': 'albersUsa'},width=700,height=400
).transform_lookup(
   lookup='State',from_=alt.LookupData(source,'State',source.columns.values)
).transform_fold(
   source.drop('State',axis=1).columns.values,# Preserve the State column,fold the rest
   ['Similarity_to','Similarity']
).transform_filter(
   selection
).add_selection(
   selection
)

我实际上在问这个问题之前尝试过这个。但事实证明我以错误的顺序进行了转换。转换顺序很重要!

您可以在此处找到完整代码:https://deepnote.com/project/altairstackoverflow--zl7Wx2tQQ22U3D1cLcodA/%2Fnotebooks%2Fstates.ipynb#00011-ed9a9249-2c34-412c-a091-d87d0ddb457d