Vega-Lite Choropleth Map滑块绑定及无数据样式问题求助
Vega-Lite choropleth地图问题解决
我在制作Vega-Lite choropleth地图时遇到两个问题:
- 年份选择滑块无法关联数据
- 部分无数据国家显示空白,希望设置为浅灰色填充或仅显示轮廓
以下是修复后的完整代码:
{ "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "width": 1050, "height": 500, "params": [ { "name": "year_selection", "value": 2020, "bind": { "input": "range", "min": 1880, "max": 2040, "step": 1, "name": "年份选择: " } } ], "projection": {"type": "equalEarth"}, "layer": [ { "data": { "url": "https://raw.githubusercontent.com/Clairinechendra/FIT3179_A2/main/ne/ne_100m_ocean.json", "format": {"type": "topojson", "feature": "oceans"} }, "mark": {"type": "geoshape", "fill": "#f2f2f2"} }, { "data": { "url": "https://raw.githubusercontent.com/Clairinechendra/FIT3179_A2/main/ne/ne_110m_graticules_30.json", "format": {"type": "topojson", "feature": "ne_110m_graticules_30"} }, "mark": {"type": "geoshape", "fill": null, "stroke": "lightgray"} }, { "data": { "url": "https://raw.githubusercontent.com/Clairinechendra/FIT3179_A2/main/ne/ne_110m_admin_0_countries.json", "format": {"type": "topojson", "feature": "ne_110m_admin_0_countries"} }, "transform": [ { "lookup": "properties.NAME", "from": { "data": { "url": "https://raw.githubusercontent.com/Clairinechendra/FIT3179_A2/main/Edu%20Data/mean-years-of-schooling-long-run.csv" }, "key": "Entity", "fields": ["Years"], "filter": {"param": "year_selection", "field": "Year"} } }, { "calculate": "datum.Years == null ? '无数据' : datum.Years", "as": "Schooling_Years" } ], "mark": {"type": "geoshape", "stroke": "white", "strokeWidth": 0.5}, "encoding": { "color": { "field": "Schooling_Years", "type": "quantitative", "scale": { "type": "threshold", "domain": [0, 2, 4, 6, 8, 10, 12], "range": ["#fff5f0", "#fee5d9", "#fcbba1", "#fc9272", "#fb6a4a", "#ef3b2c", "#cb181d", "#99000d"] }, "value": "lightgray" }, "tooltip": [ {"field": "properties.NAME", "type": "nominal", "title": "国家"}, { "field": "Years", "type": "quantitative", "title": "平均受教育年限", "format": ",.0f", "condition": {"test": "datum.Years != null", "value": "无数据"} } ] } } ] }
关键修改点
- 滑块全局化:将
params移至顶层配置,确保所有图层都能访问年份参数,解决滑块无法关联数据的问题 - 数据关联逻辑调整:以国家地理数据为基础,通过
lookup左连接对应年份的教育数据,保留所有国家实体 - 无数据处理:设置
color的value为浅灰色,当Years字段为空时自动应用;同时在tooltip中添加无数据提示 - 图层顺序优化:调整图层顺序,确保海洋、经纬网在底层,国家图层在上层,避免遮挡
内容的提问来源于stack exchange,提问作者Clairine
相关产品推荐
相关产品推荐

