如何在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
相关产品推荐
相关产品推荐

