Rag*_*rok 1 python data-visualization choropleth altair
我在 Altair 中使用美国州级数据创建了一个等值线地图。但是,我没有某些州的数据。默认情况下,这些州根本不会出现在地图上。这是一个示例图像:
我希望空状态在地图上显示为灰色。Altair 文档显示了另一个符合此描述的地图:
我的问题是如何使第一张地图中具有空值的状态看起来像第二张地图中的状态。我尝试了几件事。这是我的原始地图代码:
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
)
Run Code Online (Sandbox Code Playgroud)
这是第二张地图的代码:
# US states background
alt.Chart(states).mark_geoshape(
fill='lightgray',
stroke='white'
).properties(
title='US State Capitols',
width=700,
height=400
).project('albersUsa')
Run Code Online (Sandbox Code Playgroud)
我尝试的主要事情是在第一张地图上应用第二张地图的填充和描边参数:
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
)
Run Code Online (Sandbox Code Playgroud)
我可以用这种方式更改带有值的状态轮廓的颜色,但无法用空值填充状态。
有没有解决地图上缺失数据问题的好方法?
一种方法是使用具有所需背景的分层图表。你没有提供你的数据,所以我实际上不能尝试,但它可能看起来像这样:
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
Run Code Online (Sandbox Code Playgroud)
编辑:另一种可能的方法是使用条件编码,类似于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
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1233 次 |
| 最近记录: |