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

Vega Lite渐变条形图:基于数值的条件颜色配置问题

Vega Lite渐变条形图颜色设置问题

我在Vega Lite中为渐变条形图基于数值设置颜色时遇到了问题:使用编码区的color条件配置可以修改条形的整体颜色,但标记区里的渐变颜色条件无法生效。

编码区可生效的color配置代码:

"color": {
  "condition": [{"test": "datum['b'] < 0", "value": "red"}],
  "value": "green"
}

完整代码如下:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "A bar chart with negative values. We can hide the axis domain line, and instead use a conditional grid color to draw a zero baseline.",
  "data": {
    "values": [
      {"a": "A", "b": -28},
      {"a": "B", "b": 55},
      {"a": "C", "b": -33},
      {"a": "D", "b": 91},
      {"a": "E", "b": 81},
      {"a": "F", "b": 53},
      {"a": "G", "b": -19},
      {"a": "H", "b": 87},
      {"a": "I", "b": 52}
    ]
  },
  "mark": {
    "type": "bar",
    "color": {
      "x1": 1,
      "y1": 1,
      "x2": 1,
      "y2": 0,
      "gradient": "linear",
      "stops": [
        {
          "offset": 0,
          "color": {
            "condition": [{"test": "datum['b'] < 0", "value": "black"}],
            "value": "white"
          }
        },
        {"offset": 1,
         "color": {
            "condition": [{"test": "datum['b'] > 0", "value": "white"}],
            "value": "black"
          }
        }
      ]
    }
  },
  "encoding": {
    "x": {
      "field": "a",
      "type": "nominal",
      "axis": {
        "domain": false,
        "ticks": false,
        "labelAngle": 0,
        "labelPadding": 4
      }
    },
    "y": {
      "field": "b",
      "type": "quantitative",
      "axis": {
        "gridColor": {
          "condition": {"test": "datum.value === 0", "value": "black"},
          "value": "#ddd"
        }
      }
    },
    "color": {
      "condition": [{"test": "datum['b'] < 0", "value": "red"}],
      "value": "green"
    }
  }
}

我希望实现的效果是:正负值的渐变显示逻辑一致,即0值对应黑色,10对应白色,-10也对应白色,与当前效果相反。

内容的提问来源于stack exchange,提问作者karra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 23:30:31