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

如何在Vega-Lite中实现分组堆叠条形图左右侧分别使用绿蓝渐变配色

解决方案

你配置的核心问题是两个layer的mark属性中都写死了固定色值,直接覆盖了encoding里配置的按Activity_Type区分的梯度配色规则,只需要做少量调整即可实现目标效果:

  • 移除两个layer的mark配置中的color固定值字段,避免覆盖动态配色规则
  • (可选)添加order编码固定堆叠顺序,保证不同渲染环境下堆叠顺序一致

调整后的完整配置如下:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "values"  : [
      {"Team" : "X", "Task" : "A", "Done" : 56.5, "Planned" : 80, "Activity_Type" : "TypeA"},
      {"Team" : "X", "Task" : "A", "Done" : 26, "Planned" : 14, "Activity_Type" : "TypeB"},
      {"Team" : "X", "Task" : "B", "Done" : 26, "Planned" : 21, "Activity_Type" : "TypeA"},
      {"Team" : "X", "Task" : "B", "Done" : 16.5, "Planned" : 36, "Activity_Type" : "TypeB"},
      {"Team" : "X", "Task" : "C", "Done" : 41.5, "Planned" : 59, "Activity_Type" : "TypeA"},
      {"Team" : "X", "Task" : "C", "Done" : 9, "Planned" : 12, "Activity_Type" : "TypeB"}
    ] 
  },
  "height" : 200,
  "width" : 500,
  "encoding": {
    "tooltip" : [
      {"field" : "Team"},
      {"field" : "Task"},
      {"field" : "Done"},
      {"field" : "Planned"},
      {"field" : "Activity_Type"}
    ],
    "y": {"axis": {"title": "Number of points"}, "stack": true},
    "x": {"field": "Task", "type": "nominal", "axis": {"labelAngle": 0}}
  },
  "layer": [
    {
      "mark": {"type": "bar", "xOffset": -16, "size": 30},
      "encoding": {
        "y": {
          "field": "Done",
          "type": "quantitative"
        },
        "color": {
          "field": "Activity_Type",
          "type": "nominal",
          "scale": {
            "range": ["#81c784", "#629b65"]
          },
          "title": "Activity_Type",
          "legend" : null
        },
        "order": {"field": "Activity_Type"}
      }
    },
    {
      "mark": {"type": "bar", "size": 30, "xOffset": 16},
      "encoding": {
        "y": {
          "field": "Planned",
          "type": "quantitative"
        },
        "color": {
          "field": "Activity_Type",
          "type": "nominal",
          "scale": {
            "range": ["#1e88e5", "#2f75b3"]
          },
          "legend" : null
        },
        "order": {"field": "Activity_Type"}
      }
    }
  ]
}

我额外给y轴加了stack: true显式声明堆叠逻辑,同时删掉了配色范围里多余的第三个颜色值(你只有两类Activity_Type,两个颜色足够),你可以根据自己的需求再调整色值、条形大小和偏移量。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 11:39:05