You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Altair choropleth分级地图非高亮区域设置固定填充色方法求助

Altair 分级地图未匹配行政区自定义填充色实现方案

核心修改逻辑

未匹配到IncidentDate字段的行政区数据值为缺失值,直接通过Altair颜色比例尺内置的missing参数即可指定缺失值的固定填充色,无需额外新增字段或复杂逻辑。

修改后完整代码

import altair as alt
from vega_datasets import data
boroughs = alt.topo_feature(data.londonBoroughs.url, 'boroughs')
centroids = data.londonCentroids.url

background = alt.Chart(boroughs).mark_geoshape(
    stroke='white',
    strokeWidth=1
).encode(
    # 仅修改此处颜色编码配置即可
    color=alt.Color(
        'IncidentDate:Q',
        title='事件日期',
        # missing参数指定缺失值(即未匹配到的行政区)的填充色,可替换为任意自定义色值
        scale=alt.Scale(missing='lightgray')
    )
).transform_lookup(lookup = 'id',
    from_ = alt.LookupData(top_10v2,'Borough',['IncidentDate'])).properties(
    width=700,
    height=500
)

labels = alt.Chart(centroids).mark_text().encode(
    longitude='cx:Q',
    latitude='cy:Q',
    text='bLabel:N',
    size=alt.value(8),
    opacity=alt.value(0.6)
).transform_calculate(
    "bLabel", "indexof (datum.name,' ') > 0  ? substring(datum.name,0,indexof(datum.name, ' ')) : datum.name"
)


lines = alt.Chart(boroughs).mark_geoshape(
    filled=False,
    strokeWidth=1
).encode(color=alt.value('#eee'))

background+labels+lines

扩展方案(适合复杂判断逻辑场景)

如果后续需要自定义高亮判断规则,可使用条件编码实现,效果和上述配置完全一致:

color=alt.condition(
    # 判断条件:IncidentDate值有效即为匹配到的高亮行政区
    'isValid(datum.IncidentDate)',
    # 匹配成功使用原数值配色逻辑
    alt.Color('IncidentDate:Q', title='事件日期'),
    # 匹配失败使用固定灰色
    alt.value('lightgray')
)

内容的提问来源于stack exchange,提问作者Jimmy K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:15:08