在Altair等值线图中处理缺失值/空值

问题描述 投票:0回答:1

我在Altair用美国州级数据创建了一个等值线图。但是,我没有一些州的数据。默认情况下,这些状态根本不会出现在地图上。这是一个示例图像:

enter image description here

我希望null状态在地图上显示为灰色。 Altair文档显示了符合此描述的另一个地图:

enter image description here

我的问题是如何使第一个地图中具有空值的状态看起来像第二个地图中的状态。我试了几件事。这是我原始地图的代码:

states = alt.topo_feature(data.us_10m.url, 'states')
source = df

alt.Chart(states).mark_geoshape().encode(
    color=alt.Color('avg_prem:Q')
).transform_lookup(
    lookup='id',
    from_=alt.LookupData(source, 'id', ['avg'])
).project(
    type='albersUsa'
).properties(
    width=700,
    height=450
) 

这是第二张地图的代码:

# US states background
alt.Chart(states).mark_geoshape(
    fill='lightgray',
    stroke='white'
).properties(
    title='US State Capitols',
    width=700,
    height=400
).project('albersUsa')

我尝试的主要是在第一张地图上应用第二张地图的填充和描边参数:

alt.Chart(states).mark_geoshape(fill='lightgray',
    stroke='white').encode(
    color=alt.Color('avg_prem:Q')
).transform_lookup(
    lookup='id',
    from_=alt.LookupData(source, 'id', ['avg'])
).project(
    type='albersUsa'
).properties(
    width=700,
    height=450
) 

我可以使用这种方式更改状态轮廓的颜色,但无法用空值填充状态。

有没有一种好方法可以解决地图上缺少的数据问题?

python data-visualization choropleth altair
1个回答
2
投票

一种方法是使用具有所需背景的分层图表。你没有提供你的数据,所以我实际上无法尝试,但它可能看起来像这样:

states = alt.topo_feature(data.us_10m.url, 'states')
source = df

foreground = alt.Chart(states).mark_geoshape().encode(
    color=alt.Color('avg_prem:Q')
).transform_lookup(
    lookup='id',
    from_=alt.LookupData(source, 'id', ['avg'])
).project(
    type='albersUsa'
).properties(
    width=700,
    height=400
)  

background = alt.Chart(states).mark_geoshape(
    fill='lightgray',
    stroke='white'
).properties(
    title='US State Capitols',
    width=700,
    height=400
).project('albersUsa')

background + foreground

编辑:另一种可能的方法是使用条件编码,类似于https://vega.github.io/vega-lite/examples/point_invalid_color.html

alt.Chart(states).mark_geoshape().encode(
    color=alt.condition('datum.avg_prem !== null', 'avg_prem:Q', alt.value('lightgray'))
).transform_lookup(
    lookup='id',
    from_=alt.LookupData(source, 'id', ['avg'])
).project(
    type='albersUsa'
).properties(
    width=700,
    height=400
)  
© www.soinside.com 2019 - 2024. All rights reserved.