如何在Vega-Lite中实现自定义值域颜色映射规则?
调整Vega-Lite热力图颜色尺度为固定中点渐变
需求:已将热力图颜色范围设为红、白、绿,需修改数值绑定规则——最小值到16之间从红过渡到白,16到最大值之间从白过渡到绿,避免交叉颜色(低于16无绿色,高于16无红色)。
解决方案
在颜色编码的scale配置中添加domainMid: 16,指定固定中点值即可实现两段式渐变效果。
修改后的完整代码
{ "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "data": { "url": "data/seattle-weather.csv" }, "title": "Daily Max Temperatures (C) in Seattle, WA", "config": { "view": { "strokeWidth": 0, "step": 13 }, "axis": { "domain": false } }, "mark": "rect", "encoding": { "x": { "field": "date", "timeUnit": "date", "type": "ordinal", "title": "Day", "axis": { "labelAngle": 0, "format": "%e" } }, "y": { "field": "date", "timeUnit": "month", "type": "ordinal", "title": "Month" }, "color": { "field": "temp_max", "aggregate": "max", "type": "quantitative", "scale": { "range": [ "red", "white", "green" ], "domainMid": 16 // 新增:指定颜色尺度的固定中点 }, "legend": { "title": null } } } }
关键修改说明
domainMid: 16:强制颜色尺度以16为中间分界点,将数值范围划分为「最小值-16」「16-最大值」两段- 配合
range: ["red", "white", "green"],实现第一段从红到白、第二段从白到绿的平滑渐变 - 无需额外配置,Vega-Lite会自动匹配数据的实际最小/最大值与尺度区间
内容的提问来源于stack exchange,提问作者Nexter1
相关产品推荐
相关产品推荐

