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

如何实现带不同聚合方式的单选列选择Altair图表?

解决方案

要实现按单选切换列并对应不同聚合,核心是根据参数动态选择聚合逻辑,同时处理分类字段与数值字段的类型差异。以下是修正后的代码:

input_selector = alt.binding_radio(
    options=['GrantType', 'AwardAmount'],
    name="Display: "
)

input_param = alt.param(
    value='GrantType',
    bind=input_selector
)

radial_1 = alt.Chart(df).mark_arc(innerRadius=30, stroke='#fff').encode(
    theta=alt.Theta('agg_value:Q', stack=True),
    radius=alt.Radius('agg_value:Q', scale=alt.Scale(type='sqrt', zero=True, rangeMin=20)),
    order=alt.Order('agg_value:Q'),
    color=alt.Color(
        'GrantType:N',
        # 根据选中参数动态调整排序逻辑
        sort=alt.condition(
            alt.datum[input_param.name] == 'GrantType',
            alt.EncodingSortField('GrantType', op='count', order='descending'),
            alt.EncodingSortField('AwardAmount', op='sum', order='descending')
        ),
        scale=alt.Scale(domain=funding_source_list, range=select_colors)
    )
).transform_aggregate(
    # 按GrantType分组,根据参数选择聚合方式
    agg_value=alt.condition(
        alt.param(input_param.name) == 'GrantType',
        'count()',
        'sum(AwardAmount)'
    ),
    groupby=['GrantType']
).add_params(input_param)

关键修改点说明:

  • 动态聚合:通过transform_aggregate结合alt.condition,根据input_param的值选择对GrantType计数,或对AwardAmount求和,同时按GrantType分组,确保每个分类对应一个聚合值。
  • 类型适配:原来直接用原始字段input:Q会因为GrantType是字符串类型报错,现在统一使用聚合后的数值字段agg_value:Q,解决类型不匹配问题。
  • 动态排序:颜色的排序逻辑也通过alt.condition跟随参数切换,保证选中AwardAmount时按求和值排序,选中GrantType时按计数排序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 05:10:01