如何在带下拉菜单的Vega-Lite分级统计图中设置差异化颜色编码
为Vega-Lite下拉切换的分级统计图设置差异化配色或反转配色
要实现下拉选项对应不同配色方案或反转其中一个配色,可通过Vega-Lite的条件表达式(expr)结合参数Select来实现,以下是两种可行方案:
方案1:为两个选项设置不同Color Scheme
修改encoding.color.scale部分,根据Select的当前值动态切换配色方案:
"encoding": { "color": { "field": "varSelected", "type": "quantitative", "title": null, "scale": { "expr": "Select === 'Climate Vulnerability' ? {name: 'turbo', count: 5} : {name: 'viridis', count: 5}" } }, "tooltip": [ {"field": "name", "title": "Country"}, {"field": "varSelected", "title": "Score", "type": "quantitative"} ] }
此配置中,选择「Climate Vulnerability」时使用turbo配色,选择「Overall Vulnerability Index」时切换为viridis配色,可根据需求替换为其他Vega支持的配色方案名称。
方案2:反转其中一个数据列的配色方案
若仅需对特定选项反转现有配色,修改encoding.color.scale的reverse属性为条件表达式:
"encoding": { "color": { "field": "varSelected", "type": "quantitative", "title": null, "scale": { "scheme": {"name": "turbo", "count":5}, "reverse": {"expr": "Select === 'Overall Vulnerability Index'"} } }, "tooltip": [ {"field": "name", "title": "Country"}, {"field": "varSelected", "title": "Score", "type": "quantitative"} ] }
当选择「Overall Vulnerability Index」时,turbo配色会被反转;选择另一选项时保持原配色方向。
完整修改代码(方案1示例)
{"$schema": "https://vega.github.io/schema/vega-lite/v5.json", "config": { "background":"white", "view": {"stroke": "transparent"} }, "width": 700, "height": 500, "data": { "url": "https://unpkg.com/world-atlas@1.1.4/world/110m.json", "format": { "type": "topojson", "feature": "countries" } }, "projection": { "type": "naturalEarth2" }, "mark": { "type": "geoshape", "stroke": "rgb(50, 50, 50)", "strokeWidth":0.3 }, "transform": [ {"calculate":"parseInt(datum.id)", "as":"id_N"}, { "lookup": "id_N", "from": { "key": "id", "fields": ["alpha3", "name"], "data": {"url": "data1"} } }, { "lookup": "alpha3", "from":{ "data":{ "url":"data2"}, "key": "ISO3", "fields":["Vulnerability", "Gain"] } }, {"calculate": "datum.Vulnerability", "as": "Climate Vulnerability"}, {"calculate": "datum.Gain", "as": "Overall Vulnerability Index"}, {"calculate": "datum[Select]","as": "varSelected"} ], "params": [ {"name": "Select", "value": "Climate Vulnerability", "bind": { "input": "select", "options": [ "Climate Vulnerability", "Overall Vulnerability Index"]}} ], "encoding": { "color":{ "field":"varSelected", "type":"quantitative", "title": null, "scale": { "expr": "Select === 'Climate Vulnerability' ? {name: 'turbo', count: 5} : {name: 'viridis', count: 5}" } }, "tooltip":[ {"field":"name", "title":"Country"}, {"field":"varSelected","title":"Score","type":"quantitative"} ] } }
内容的提问来源于stack exchange,提问作者Novice
相关产品推荐
相关产品推荐

