如何在Vega-Lite中结合param与数据集字段设置stroke属性条件?
解决Vega-Lite中hover时仅count>0的矩形显示黑色边框的问题
问题出在你对highlight参数的判断逻辑上——当select类型为point时,highlight存储的是选中的数据对象而非布尔值,直接用highlight && datum.count > 0无法正确触发条件。
正确的做法是在condition中同时指定触发参数和数据判断条件:
- 用
param: "highlight"指定hover触发的参数 - 用
test: "datum.count > 0"过滤出count大于0的元素
修改后的stroke配置如下:
"stroke": { "condition": { "param": "highlight", "test": "datum.count > 0", "value": "black" }, "value": null }
完整的代码示例:
{ "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "data": { "values": [ {"actual": "A", "predicted": "A", "count": 13}, {"actual": "A", "predicted": "B", "count": 0}, {"actual": "A", "predicted": "C", "count": 0}, {"actual": "B", "predicted": "A", "count": 0}, {"actual": "B", "predicted": "B", "count": 10}, {"actual": "B", "predicted": "C", "count": 6}, {"actual": "C", "predicted": "A", "count": 0}, {"actual": "C", "predicted": "B", "count": 0}, {"actual": "C", "predicted": "C", "count": 9} ] }, "params": [ {"name": "highlight", "select": {"type": "point", "on": "pointerover"}} ], "mark": {"type": "rect", "strokeWidth": 2}, "encoding": { "y": {"field": "actual", "type": "nominal"}, "x": {"field": "predicted", "type": "nominal"}, "fill": {"field": "count", "type": "quantitative"}, "stroke": { "condition": { "param": "highlight", "test": "datum.count > 0", "value": "black" }, "value": null }, "opacity": {"condition": {"param": "highlight", "value": 1}, "value": 0.5}, "order": {"condition": {"param": "highlight", "value": 1}, "value": 0} }, "config": { "scale": {"bandPaddingInner": 0, "bandPaddingOuter": 0}, "view": {"step": 40}, "range": {"ramp": {"scheme": "yellowgreenblue"}}, "axis": {"domain": false} } }
这样配置后,只有当鼠标hover到count>0的矩形时,才会显示黑色边框;hover到count=0的矩形时,不会触发边框样式。
内容的提问来源于stack exchange,提问作者Tri Nguyen
相关产品推荐
相关产品推荐

