【问题标题】:Altair: geo_shape doesn't work with selectionAltair:geo_shape 不适用于选择
【发布时间】:2021-07-03 09:13:05
【问题描述】:

我正在制作一张显示不同州之间相似性的 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',
    tooltip = ['Similarity:Q']
).properties(
    projection={'type': 'albersUsa'},
    width=700,
    height=400
).transform_lookup(
    lookup='State',
    from_=alt.LookupData(source, 'State', source.columns.values)
).transform_filter(
    selection
).add_selection(
    selection
)

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

【问题讨论】:

  • 您能否尝试使用 vega 示例数据集来重现此内容,以确定您的数据或代码是否存在某些问题,并使其他人更容易重现?这是一个从altair-viz.github.io/gallery/choropleth.html开始的示例
  • 它适用于示例数据。但那个数据是不同的。我的 DatasetA 有多个与查找键匹配的值。例如。每个状态都与另一个状态进行比较,这意味着我有 2500 行数据,每个状态在我的键列中出现 50 次。但是查找匹配键的第一次出现。这是我的数据集的代码和 vega 数据集的代码的链接:deepnote.com/project/altairstackoverflow--zl7Wx2tQQ22U3D1cLcodA/…

标签: altair vega-lite vega


【解决方案1】:

我通过使用 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

【讨论】:

    猜你喜欢
    • 2021-05-13
    • 1970-01-01
    • 2015-07-07
    • 2018-10-18
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多