添加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"} } }
关键逻辑说明
- 聚合总计数:通过
aggregate分组计算每个国家的总计数,存入临时数据集country_totals - 关联原始数据:用
lookup把总计数字段带入原始数据行,为后续排序筛选做准备 - 计算排名:
window函数按总计数降序为每个国家生成排名 - 筛选目标国家:
filter只保留排名≤3的国家数据
这样既保证了只显示总计数最高的3个国家,又保留了每个国家的产品明细数据,实现堆叠柱状图的需求。
内容的提问来源于stack exchange,提问作者Pirate X
相关产品推荐
相关产品推荐

