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

如何在Vega-Lite中将数据集分组为Top-K项加其余合并项

你完全可以在Vega-Lite内部实现这个需求,不需要在JavaScript端或者服务端提前处理数据,也不会破坏原始数据结构。

核心要用到joinaggregate转换替代普通的aggregate,它可以将聚合计算的结果作为新字段追加到每一行原始数据中,不会将数据聚合为国家维度的汇总结构。以下是可用的transform配置:

"transform": [
  // 把每个国家全年总访问量追加到所有对应原始数据行,不改变原始数据结构
  {
    "joinaggregate": [
      {"op": "sum", "field": "hits", "as": "hit_sum_by_country"}
    ],
    "groupby": ["country"]
  },
  // 全局按国家总访问量倒序排秩
  {
    "window": [{"op": "dense_rank", "as": "country_rank"}],
    "sort": [{"field": "hit_sum_by_country", "order": "descending"}]
  },
  // 生成top_country字段,前5保留原名,其余归为OTHER
  {
    "calculate": "datum.country_rank <= 5 ? datum.country : 'OTHER'",
    "as": "top_country"
  },
  // 按日期和top_country聚合每日访问量,用于绘图
  {
    "aggregate": [{"op": "sum", "field": "hits", "as": "daily_hits"}],
    "groupby": ["dates", "top_country"]
  }
]

后续绘图时,x轴绑定dates字段,y轴绑定daily_hits字段,颜色维度绑定top_country字段即可得到符合要求的堆叠条形图。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:36:07