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

Vega-Lite饼图如何实现多类别图例选择并重新计算占比?

Vega-Lite 实现饼图多类别选择及动态占比计算

要实现多类别选择并自动重新计算饼图占比,只需调整选择器类型、添加数据过滤逻辑,具体步骤如下:

1. 配置多选选择器

将选择器的type从single改为multi,并绑定到复选框控件,支持同时勾选多个类别:

"selection": {
  "categorySelect": {
    "type": "multi",
    "fields": ["category"],
    "bind": {
      "input": "checkbox",
      "options": ["类别1", "类别2", "类别3", "类别4", "类别5", "类别6"],
      "name": "选择要展示的类别: "
    }
  }
}

2. 添加数据过滤逻辑

在transform中设置过滤规则,仅保留选中的类别;若未选中任何类别,则默认展示全部数据:

"transform": [
  {
    "filter": {
      "or": [
        {"selection": "categorySelect"},
        {"not": {"selection": "categorySelect"}}
      ]
    }
  }
]

3. 动态计算饼图占比

饼图角度基于过滤后的数据自动计算总和,只需保持theta字段绑定数值列并开启堆叠即可:

"mark": {"type": "arc"},
"encoding": {
  "theta": {"field": "value", "type": "quantitative", "stack": true},
  "color": {"field": "category", "type": "nominal"}
}

完整示例代码

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "values": [
      {"category": "类别1", "value": 10},
      {"category": "类别2", "value": 20},
      {"category": "类别3", "value": 15},
      {"category": "类别4", "value": 25},
      {"category": "类别5", "value": 12},
      {"category": "类别6", "value": 18}
    ]
  },
  "selection": {
    "categorySelect": {
      "type": "multi",
      "fields": ["category"],
      "bind": {
        "input": "checkbox",
        "options": ["类别1", "类别2", "类别3", "类别4", "类别5", "类别6"],
        "name": "选择要展示的类别: "
      }
    }
  },
  "transform": [
    {
      "filter": {
        "or": [
          {"selection": "categorySelect"},
          {"not": {"selection": "categorySelect"}}
        ]
      }
    }
  ],
  "mark": {"type": "arc"},
  "encoding": {
    "theta": {"field": "value", "type": "quantitative", "stack": true},
    "color": {"field": "category", "type": "nominal"},
    "tooltip": [
      {"field": "category", "type": "nominal"},
      {"field": "value", "type": "quantitative"}
    ]
  }
}

关键说明

  • 多选选择器通过type: "multi"实现,绑定复选框后用户可自由勾选多个目标类别;
  • 过滤逻辑兼顾了"未选任何类别时展示全部数据"的场景,避免出现空图表;
  • 饼图的theta字段开启stack: true后,会自动基于过滤后的数据总和重新计算每个类别的占比,无需额外手动处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 09:02:26