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

如何在Vega-Lite中实现堆叠与分组组合条形图并修复重叠问题

Vega-Lite:堆叠+分组条形图实现方案

需求说明

要实现每个年份分组包含两个条形:一个将「Earned Income」与「Funding Income」堆叠在一起,另一个单独展示「Expenses」。之前用layer实现时出现了条形重叠的问题。

修复后的完整代码

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "values": [
      {"Year": 2022, "Group": "Funding Income", "Value": 7000},
      {"Year": 2022, "Group": "Earned Income", "Value": 3000},
      {"Year": 2022, "Group": "Expenses", "Value": 8000},
      {"Year": 2021, "Group": "Funding Income", "Value": 6000},
      {"Year": 2021, "Group": "Earned Income", "Value": 3000},
      {"Year": 2021, "Group": "Expenses", "Value": 5000}
    ]
  },
  "transform": [
    {"calculate": "datum.Group == 'Expenses' ? 'Expenses' : 'Income'", "as": "Category"}
  ],
  "encoding": {
    "x": {"field": "Year", "type": "ordinal"},
    "xOffset": {"field": "Category"},
    "y": {"field": "Value", "type": "quantitative"},
    "color": {"field": "Group"}
  },
  "layer": [
    {
      "mark": "bar",
      "transform": [{"filter": "datum.Category == 'Income'"}],
      "encoding": {
        "y": {"aggregate": "sum", "field": "Value"}
      }
    },
    {
      "mark": "bar",
      "transform": [{"filter": "datum.Category == 'Expenses'"}]
    }
  ],
  "resolve": {"scale": {"y": "shared"}}
}

核心修改说明

  • 新增分组标识:通过transform计算Category字段,把两类收入归为Income,支出单独为Expenses,用这个字段统一控制x轴偏移,从根源避免重叠。
  • 收入组堆叠设置:给收入层的y轴配置sum聚合,实现两个收入类的堆叠效果。
  • 统一偏移规则:把xOffset放在顶层encoding里,让两个layer的条形按Category自动分组排列,位置不会冲突。
  • 统一y轴刻度:配置resolve.scale.y: shared,确保收入和支出用同一y轴,视觉对比更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 08:55:17