You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 19:50:14