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

添加Vega-Lite Transform后图表空白,需展示Top3国家堆叠柱状图

解决Vega-Lite堆叠柱状图添加transform后空白的问题

问题核心

要实现“展示总计数排名前3的国家”的堆叠柱状图,关键是先计算每个国家的总计数,再基于这个总计数筛选出目标国家,最后保留这些国家的原始明细数据用于堆叠。如果transform逻辑错误(比如直接对单条数据排序、聚合后丢失原始明细),就会导致图表无数据显示。

正确实现代码

以下是完整可运行的代码,核心通过多步transform完成筛选:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "values": [
      {"country": "中国", "product": "A", "count": 10},
      {"country": "中国", "product": "B", "count": 15},
      {"country": "美国", "product": "A", "count": 8},
      {"country": "美国", "product": "B", "count": 20},
      {"country": "日本", "product": "A", "count": 12},
      {"country": "日本", "product": "B", "count": 18},
      {"country": "德国", "product": "A", "count": 5},
      {"country": "德国", "product": "B", "count": 7}
    ]
  },
  "transform": [
    // 计算每个国家的总计数,生成临时数据集
    {
      "aggregate": [{"op": "sum", "field": "count", "as": "total_count"}],
      "groupby": ["country"],
      "as": "country_totals"
    },
    // 将原始数据与临时数据集关联,带入总计数字段
    {
      "lookup": "country",
      "from": {"data": "country_totals", "key": "country", "fields": ["total_count"]},
      "as": ["total_count"]
    },
    // 按总计数降序计算国家排名
    {"window": [{"op": "rank", "field": "total_count", "as": "rank", "sort": {"field": "total_count", "order": "descending"}}]},
    // 筛选排名前3的国家
    {"filter": "datum.rank <= 3"}
  ],
  "mark": "bar",
  "encoding": {
    "x": {"field": "country", "type": "nominal"},
    "y": {"field": "count", "type": "quantitative", "aggregate": "sum"},
    "color": {"field": "product", "type": "nominal"}
  }
}

关键逻辑说明

  1. 聚合总计数:通过aggregate分组计算每个国家的总计数,存入临时数据集country_totals
  2. 关联原始数据:用lookup把总计数字段带入原始数据行,为后续排序筛选做准备
  3. 计算排名:window函数按总计数降序为每个国家生成排名
  4. 筛选目标国家:filter只保留排名≤3的国家数据

这样既保证了只显示总计数最高的3个国家,又保留了每个国家的产品明细数据,实现堆叠柱状图的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 01:59:56