Vega-Lite堆叠条形图:设置分类间距与固定分类顺序
解决Vega-Lite堆叠条形图的两个问题
问题1:固定堆叠分类顺序
要强制条形内的分类按指定顺序("Funding Income"、"Other"、"Expenses"、"Earned Income")堆叠,需做以下调整:
- 添加
order编码,绑定Group字段并指定自定义排序规则,确保堆叠顺序与预设一致。 - 保持
color字段的sort和scale.domain与目标顺序完全匹配,避免颜色映射混乱。
问题2:堆叠分类间添加间距
默认堆叠条形的分段紧密贴合,要添加间距可通过以下方式实现:
- 移除原mark上的全局
stroke和strokeWidth(这是整个条形的边框)。 - 给每个堆叠分段设置
stroke为背景色(示例中用白色),并设置strokeWidth为所需间隙宽度(示例设为2),分段间会显示出明显间隙。
修改后的完整代码
{ "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "data": { "values": [ { "Year": 2022, "Group": "Funding Income", "Value": 7000, "Type": "plan" }, { "Year": 2022, "Group": "Earned Income", "Value": 3000, "Type": "plan" }, { "Year": 2022, "Group": "Other", "Value": 500, "Type": "plan" }, { "Year": 2022, "Group": "Expenses", "Value": 8000, "Type": "reality" }, { "Year": 2022, "Group": "Other", "Value": 1000, "Type": "reality" }, { "Year": 2022, "Group": "Funding Income", "Value": 8000, "Type": "reality" }, { "Year": 2021, "Group": "Funding Income", "Value": 6000, "Type": "reality" }, { "Year": 2021, "Group": "Other", "Value": 700, "Type": "reality" }, { "Year": 2021, "Group": "Earned Income", "Value": 3000, "Type": "plan" }, { "Year": 2021, "Group": "Other", "Value": 1100, "Type": "plan" }, { "Year": 2021, "Group": "Funding Income", "Value": 4000, "Type": "plan" }, { "Year": 2021, "Group": "Expenses", "Value": 5000, "Type": "reality" } ] }, "facet": { "column": { "field": "Year", "type": "nominal", "header": { "labelOrient": "bottom", "labelFont": "Arial black", "labelColor": "black", "title": null } } }, "spec": { "height": 164, "layer": [ { "mark": { "type": "bar", "cornerRadius": 1, "stroke": "white", "strokeWidth": 2 }, "encoding": { "x": { "field": "Type", "axis": { "labelAngle": 0, "labelOffset": 0 }, "title": null }, "y": { "field": "Value", "type": "quantitative", "title": null }, "xOffset": {"field": "Type"}, "color": { "field": "Group", "sort": [ "Funding Income", "Other", "Expenses", "Earned Income" ], "scale": { "domain": [ "Funding Income", "Other", "Expenses", "Earned Income" ], "range": [ "gray", "white", "lightgray", "black" ] } }, "order": { "field": "Group", "sort": [ "Funding Income", "Other", "Expenses", "Earned Income" ] } } } ] } }
内容的提问来源于stack exchange,提问作者tomecsek
相关产品推荐
相关产品推荐

