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

Python多分类列交互式柱状图的图例协同问题求解

多分类协同筛选的交互式柱状图解决方案

问题背景

需要基于包含三个分类列(size/design/colors)的DataFrame,创建支持多选项切换的交互式柱状图,实现通过选择分类值来筛选显示对应的柱状条,但原有代码中三个图例无法协同工作,切换一个图例的选择会重置其他图例的状态。

数据准备

import pandas as pd

data = dict(size=['big', 'big', 'big', 'big', 'small', 'small', 'small', 'small'],
            design=['A', 'A', 'B', 'B', 'A', 'A', 'B', 'B'],
            colors=['blue', 'red', 'blue', 'red', 'blue', 'red', 'blue', 'red'],
            x=['1', '2', '3', '4', '5', '6', '7', '8'],
            y=[10, 20, 10, 30, 10, 40, 10, 30])
data = pd.DataFrame(data)

问题根源

原有代码使用单一选择器对象绑定三个图例,导致所有图例共享同一选择状态,切换任意图例都会覆盖全局选择,无法保留其他分类的筛选条件。

修复实现代码

为每个分类列创建独立的多选选择器,通过逻辑与组合筛选条件,实现多图例协同工作:

import altair as alt

# 为每个分类列创建独立的多选选择器
size_sel = alt.selection_multi(fields=['size'], name='Size')
design_sel = alt.selection_multi(fields=['design'], name='Design')
colors_sel = alt.selection_multi(fields=['colors'], name='Colors')

# 组合筛选条件:仅保留同时满足所有选中分类的数据
combined_filter = size_sel & design_sel & colors_sel

# 主柱状图:符合条件的高亮,否则灰化
main_chart = alt.Chart(data).mark_bar().encode(
    x=alt.X('x', axis=alt.Axis(title='ID Number')),
    y=alt.Y('y', axis=alt.Axis(title='Output')),
    color=alt.condition(
        combined_filter,
        alt.Color('x:N', legend=None),  # 用ID区分柱子颜色
        alt.value('lightgray')
    )
)

# 自定义Size图例,绑定对应选择器
size_legend = alt.Chart(data).mark_rect().encode(
    x=alt.X('size:O', title='Size'),
    color=alt.condition(
        size_sel,
        alt.Color('size:N'),
        alt.value('lightgray')
    )
).add_selection(size_sel)

# 自定义Design图例,绑定对应选择器
design_legend = alt.Chart(data).mark_rect().encode(
    x=alt.X('design:O', title='Design'),
    color=alt.condition(
        design_sel,
        alt.Color('design:N'),
        alt.value('lightgray')
    )
).add_selection(design_sel)

# 自定义Colors图例,绑定对应选择器
colors_legend = alt.Chart(data).mark_rect().encode(
    x=alt.X('colors:O', title='Colors'),
    color=alt.condition(
        colors_sel,
        alt.Color('colors:N'),
        alt.value('lightgray')
    )
).add_selection(colors_sel)

# 布局组合:主图左侧,三个图例垂直排列右侧
main_chart | (size_legend & design_legend & colors_legend)

关键说明

  • 每个分类列对应独立的selection_multi选择器,确保各图例的选择状态独立存储、互不干扰。
  • 使用&运算符组合选择器,实现逻辑与筛选:只有同时匹配所有选中分类条件的数据点才会高亮显示。
  • 图例的颜色反馈与对应选择器绑定,选中的分类项保持原色,未选中项灰化,直观展示当前选择状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 04:01:07