求助:Power BI中Deneb的Vega桑基图国家分组两侧间隙设置
Vega桑基图两侧国家分组加间隙的解决办法
核心调整方向
要让左右两侧都按国家分组并留出间隙,得分别给左右节点的位置计算加分组偏移逻辑——先按国家把节点归好类,再给不同国家的组之间加固定比例的间隙。
具体改法
1. 给节点数据加分组统计字段
在data里新增一个转换步骤,算出每个国家的节点数量、总流量,还有组内的排序索引:
{ "name": "nodes_with_groups", "source": "nodes", "transform": [ // 左侧节点的国家统计 { "window": [{"op": "count", "as": "country_source_num"}, {"op": "sum", "field": "value", "as": "country_source_total"}], "groupby": ["country"] }, // 右侧节点的国家统计 { "window": [{"op": "count", "as": "country_target_num"}, {"op": "sum", "field": "value", "as": "country_target_total"}], "groupby": ["country"] }, // 每个国家内的节点排序索引 { "window": [{"op": "row_number", "as": "country_idx"}], "groupby": ["country"], "sort": [{"field": "name", "order": "asc"}] }, // 间隙比例,可自己调,0.1就是10%的间隙 { "calculate": "0.1", "as": "gap_rate" } ] }
2. 修改节点位置的计算逻辑
找到marks里的sankey标记,把node的y和y2编码改成带间隙偏移的计算:
"node": { "encode": { "enter": { "x": {"scale": "x", "field": "x"}, "width": {"scale": "x", "band": 1}, "fill": {"scale": "color", "field": "name"}, "tooltip": {"field": "name"} }, "update": { "y": { "signal": "datum.x === 0 ? (datum.y0 - (datum.country_idx > 1 ? datum.country_source_total * datum.gap_rate : 0)) : (datum.y0 - (datum.country_idx > 1 ? datum.country_target_total * datum.gap_rate : 0))" }, "y2": { "signal": "datum.x === 0 ? (datum.y1 - (datum.country_idx > 1 ? datum.country_source_total * datum.gap_rate : 0)) : (datum.y1 - (datum.country_idx > 1 ? datum.country_target_total * datum.gap_rate : 0))" }, "opacity": {"value": 1} } } }
3. 关联新的数据源
把原来sankey标记的to数据源改成我们新增的nodes_with_groups:
"type": "sankey", "from": {"data": "links"}, "to": {"data": "nodes_with_groups"},
注意点
gap_rate数值可以自己调,比如改成0.15间隙会更宽- 要确保节点先按国家分组排序,不然间隙会加错位置
- 左右两侧分开判断处理,保证两边的分组间隙都生效
内容的提问来源于stack exchange,提问作者Flynn
相关产品推荐
相关产品推荐

