如何在Vega-Lite柱状图中添加指定渐变效果?
Vega-Lite柱状图添加分类渐变的解决方案
要实现不同类别柱子的渐变填充,不能直接在颜色比例尺的range里设置渐变,得通过标记的fill属性结合条件判断来实现,以下是修改后的完整配置:
{ "data": { "name": "dataset" }, "transform": [ { "fold": ["Booked", "Not Booked"], "as": ["Booking Status", "Value"] } ], "mark": { "type": "bar", "cornerRadiusEnd": 10, "fill": { "condition": [ { "test": "datum['Booking Status'] === 'Booked'", "value": { "gradient": "linear", "x1": 0, "y1": 0, "x2": 0, "y2": 1, "stops": [ {"offset": 0, "color": "white"}, {"offset": 1, "color": "green"} ] } }, { "test": "datum['Booking Status'] === 'Not Booked'", "value": { "gradient": "linear", "x1": 0, "y1": 0, "x2": 0, "y2": 1, "stops": [ {"offset": 0, "color": "white"}, {"offset": 1, "color": "red"} ] } } ] } }, "encoding": { "x": { "field": "Event Due Date", "type": "ordinal", "timeUnit": "month", "title": "", "sort": "x" }, "y": { "field": "Value", "aggregate": "sum", "type": "quantitative", "title": "" }, "color": { "field": "Booking Status", "type": "nominal", "scale": { "domain": ["Booked", "Not Booked"], "range": ["green", "red"] }, "title": "Booking Status" }, "xOffset": { "field": "Booking Status" } } }
关键修改说明
- 保留
color编码:用来维持图例的正常显示,确保分类与颜色的对应关系清晰。 - 新增
mark.fill条件配置:- 通过
test判断当前柱子的Booking Status类别。 - 针对每个类别定义线性渐变,
x1/x2设为0、y1/y2设为0/1表示渐变方向是从上到下,stops数组定义渐变的起始(白色)和结束(对应类别色)颜色。
- 通过
如果不需要图例的纯色显示,也可以直接移除color编码,仅保留fill的渐变配置。
内容的提问来源于stack exchange,提问作者Seannyyboyyyyy
相关产品推荐
相关产品推荐

