[英]Dealing with missing values / nulls in Altair choropleth map
我已經在Altair中使用美國州級數據創建了一個Choropleth地圖。 但是,我沒有某些州的數據。 默認情況下,這些狀態根本不會出現在地圖上。 這是一個示例圖像:
我希望空狀態在地圖上顯示為灰色。 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
)
這是第二張地圖的代碼:
# 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
)
我可以通過這種方式用值更改狀態輪廓的顏色,但不能用空值填充狀態。
有沒有一種好的方法可以解決地圖上丟失的數據問題?
一種方法是使用具有所需背景的分層圖表。 您沒有提供數據,所以我實際上無法嘗試,但它可能看起來像這樣:
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
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.