单击一个州以在Altair图表中显示其县

时间:2020-04-16 14:00:45

标签: python altair

我希望能够单击一个州(单选或多选)并显示选定州的县,同时仍继续显示未选定州。我可以通过构造一个数据框来实现此目的,在该数据框中,将州形状的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

1 个答案:

答案 0 :(得分:0)

我终于可以通过选择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]}


最后,我们将这两个语句与谓词组合。最终产品看起来像这样:

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")


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