【问题标题】:Clicking a state to reveal its counties in Altair chart单击一个州以在 Altair 图表中显示其县
【发布时间】:2020-04-24 21:06:21
【问题描述】:

我希望能够单击一个州(单选或多选)并显示所选州的县,同时仍继续显示未选择的州。我已经能够通过构建一个数据框来实现这一点,我将州形状的 geojson 文件附加到县形状的 geojson 中。

census_area centroid_lat    centroid_lon    county_fips fips    geometry    geomlist    id  iso_3166_2  lsad    name    state   state_fips  state_only_fips

state_fips 存在于每个元组中,其中 state_only_fips 仅存在于状态形状中。然后我使用以下代码构建我的地图:

state_selection = alt.selection_single(empty='none', fields=['properties.state_only_fips'])

alt.Chart(combined_geo).mark_geoshape(stroke='black').encode(
).add_selection(
    state_selection
).transform_filter(
    {'not': state_selection}
).properties(
    width=900,
    height=700
).project("albersUsa")

这正确地隐藏了状态形状并显示了基础县,但它表现不佳。我希望流程看起来像这样,而不是渲染所有县 州形状并仅隐藏我选择的州形状:

  1. 初始化图表,仅显示状态形状(表示为 state_only_fips 值,或 'lsad' == 'State' 的值)

  2. 如果单击了某个状态,则隐藏选定状态,同时继续显示所有其他状态

  3. 显示所选州的县形状。 Display Selected State's Counties

我觉得这是可能的,并且会使图表表现更好,但我不确定如何构建 geojson 文件和/或我的 transform_filter

【问题讨论】:

    标签: python altair


    【解决方案1】:

    我最终能够通过 2 个选择来实现这一点:1 个检查所选州,一个检查所选州的县。为了显示状态,我显示归类为“状态”且尚未被点击的形状。选择在 state_only_fips 上,它只存在于状态形状。

    state_selection = alt.selection_multi(empty='none', fields=['properties.state_only_fips'], clear='dblclick')
    
    {'and' : [('datum[\'properties.lsad\'] == \'State\''), {'not': state_selection}]}
    


    我在 state_fips 上添加了第二个选择,它包含在每个形状中。在状态形状中,它的值与 state_only_fips 相同。第二个过滤器还过滤掉所有未分类为“状态”的形状。

    county_selection = alt.selection_multi(empty='none', fields=['properties.state_fips'], clear='dblclick')
    
    {'and' : [('datum[\'properties.lsad\'] !== \'State\''), county_selection]}
    


    最后,我们将这两个语句与一个 or 谓词结合起来。最终产品如下所示:

    county_selection = alt.selection_multi(empty='none', fields=['properties.state_fips'], clear='dblclick')
    state_selection = alt.selection_multi(empty='none', fields=['properties.state_only_fips'], clear='dblclick')
    
    base_chart = alt.Chart().mark_geoshape(stroke='black').encode(
    ).add_selection(
        state_selection,
        county_selection
    ).transform_filter(
        {'or': [{'and' : [('datum[\'properties.lsad\'] == \'State\''), {'not': state_selection}]}
            ,{'and' : [('datum[\'properties.lsad\'] !== \'State\''), county_selection]}]}
    ).properties(
        width=900,
        height=700
    ).project("albersUsa")
    


    这可能可以以更有效的方式完成,但它的工作负载比以前更好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 2021-03-14
      • 2021-09-27
      • 1970-01-01
      相关资源
      最近更新 更多