如何在Vega-Lite中基于嵌套对象布尔值实现条件颜色编码?
问题:Vega-Lite中基于嵌套对象属性的条件颜色编码失效
背景
我给cars.json数据集的每条记录添加了嵌套的annotation对象,用来标记是否选中,修改后的数据片段如下:
[ { "annotation": {"selected" : true}, "Name":"chevrolet chevelle malibu", "Miles_per_Gallon":18, "Horsepower":130 }, { "annotation": {"selected": false}, "Name":"buick skylark 320", "Miles_per_Gallon":15, "Horsepower": 165 } ]
我想基于annotation.selected的布尔值给散点设置条件颜色:选中的点显示黄色,未选中的显示steelblue,于是编写了如下Vega-Lite配置:
{ "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "description": "A scatterplot showing horsepower and miles per gallons for various cars.", "data": {"url": "data/cars.json"}, "mark": "point", "encoding": { "x": {"field": "Horsepower", "type": "quantitative"}, "y": {"field": "Miles_per_Gallon", "type": "quantitative"}, "color": { "condition": { "test": "datum['annotation'].selected === true", "value": "yellow" }, "value": "steelblue" } } }
但所有点都显示为steelblue,条件规则未生效,请问如何解决?
解决方案
问题出在三个地方,逐一修正即可:
原始数据的语法错误
- 第一条数据的
Horsepower字段后多了一个逗号,会导致JSON解析失败; - 第二条数据缺少
Miles_per_Gallon字段,会导致该点无法正常渲染,建议补全字段值。
- 第一条数据的
Vega表达式的写法问题
- 在Vega的测试表达式中,直接访问嵌套属性时,最好先判断
annotation是否存在(避免缺失该字段的记录报错),同时布尔值可以直接作为判断条件,无需=== true。推荐写法:datum.annotation && datum.annotation.selected - 如果你习惯用括号语法,也可以写成
datum['annotation']['selected'],但同样要先判断父对象存在。
- 在Vega的测试表达式中,直接访问嵌套属性时,最好先判断
配置中的语法错误
- 原始配置里的
y字段配置没有闭合大括号,导致整个JSON结构无效,需要在"type": "quantitative"后添加}。
- 原始配置里的
修正后的完整配置
{ "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "description": "A scatterplot showing horsepower and miles per gallons for various cars.", "data": {"url": "data/cars.json"}, "mark": "point", "encoding": { "x": {"field": "Horsepower", "type": "quantitative"}, "y": {"field": "Miles_per_Gallon", "type": "quantitative"}, "color": { "condition": { "test": "datum.annotation && datum.annotation.selected", "value": "yellow" }, "value": "steelblue" } } }
修正后,带有annotation.selected: true的点会显示黄色,其余显示steelblue。
内容的提问来源于stack exchange,提问作者ptacek
相关产品推荐
相关产品推荐

