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

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%"}
      }
    }
  ]
}

关键修改说明

  1. 指定y轴排序规则:在每个图层的y字段配置中加入"sort": {"field": "Good %", "order": "descending"},直接引用原始数据的Good %字段作为排序依据(需要升序则将descending改为ascending)。
  2. 同步所有图层排序:因为是分层图表,三个图层的y轴排序规则必须完全一致,否则会出现文本与条形错位的问题。

原问题原因

折叠(fold)转换后,每个Question会生成两条记录(分别对应Good %和Bad %),此时直接用折叠后的数据排序会导致同一Question的两条记录排序冲突。而引用原始数据集的Good %字段时,Vega Lite会自动取每个Question对应的唯一Good %值作为排序依据,不受折叠后数据的影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 12:10:20