PowerBI Deneb(Vega Lite)如何按折叠后的Good %指标排序?
解决方案:按Good %排序Question
要实现按Good %对Question排序,核心是基于原始数据集里的Good %字段指定排序规则,而非折叠后的数据(折叠后每个Question对应两条记录,无法直接用于排序)。
修改后的Vega Lite代码
{ "data": {"name": "dataset"}, "width": 500, "height": {"step": 15}, "layer": [ { "name": "BAR", "mark": {"type": "bar", "size": 14}, "transform": [ { "fold": ["Good %", "Bad %"], "as": ["key", "value"] }, { "calculate": "indexof(['Good %', 'Bad %'], datum.key)", "as": "order" } ], "encoding": { "y": { "field": "Question", "type": "nominal", "sort": {"field": "Good %", "order": "descending"}, // 新增排序规则:按Good %降序 "axis": { "labelAlign": "right", "labelLimit": 400, "labelFont": "DIN", "labelFontSize": 10, "orient": "left", "title": null, "labelColor": "white", "minExtent": 400 } }, "x": { "field": "value", "type": "quantitative", "title": null, "axis": {"grid": false, "ticks": false, "labels": false} }, "color": { "field": "key", "type": "nominal", "legend": null, "scale": { "domain": ["Bad %", "Good %"], "range": ["#DE3E33", "#1AA14D"] } }, "order": {"field": "order", "type": "ordinal"} } }, { "mark": {"type": "text", "align": "right", "x": -10}, "encoding": { "y": {"field": "Question", "type": "nominal", "sort": {"field": "Good %", "order": "descending"}}, // 同步排序规则 "color": { "condition": {"test": "datum['Good %'] >= 0.5", "value": "green"}, "value": "red" }, "text": {"field": "Question", "type": "nominal"} } }, { "mark": {"type": "text", "align": "left", "x": 2}, "encoding": { "y": {"field": "Question", "type": "nominal", "sort": {"field": "Good %", "order": "descending"}}, // 同步排序规则 "color": {"value": "white"}, "text": {"aggregate": "sum", "field": "Good %", "type": "quantitative", "format": ".0%"} } } ] }
关键修改说明
- 指定y轴排序规则:在每个图层的
y字段配置中加入"sort": {"field": "Good %", "order": "descending"},直接引用原始数据的Good %字段作为排序依据(需要升序则将descending改为ascending)。 - 同步所有图层排序:因为是分层图表,三个图层的
y轴排序规则必须完全一致,否则会出现文本与条形错位的问题。
原问题原因
折叠(fold)转换后,每个Question会生成两条记录(分别对应Good %和Bad %),此时直接用折叠后的数据排序会导致同一Question的两条记录排序冲突。而引用原始数据集的Good %字段时,Vega Lite会自动取每个Question对应的唯一Good %值作为排序依据,不受折叠后数据的影响。
内容的提问来源于stack exchange,提问作者Worthywow
相关产品推荐
相关产品推荐

