Altair 无法创建选择组合

altair can't create combination of selections

我想创建一个交互式 'legend',允许我 select 组合不同列中的数据。 例如,如果我们有以下数据:

data = {
    'type1': [1, 0, 0, 1, 0, 1],
    'type2': [1, 1, 1, 1, 0, 0],
    'type3': [1, 0, 0, 1, 1, 0],
    'id': ['test1', 'test2', 'test3', 'test4', 'test5', 'test6'],
    'fuel': [1, 10, 30, 50, 25, 20]
}
df = pd.DataFrame(data, columns=['id', 'fuel', 'type1', 'type2', 'type3'])

这导致:

我现在想要可视化不同 'types' 的组合的能力。
像这样:

因此,如果我仅切换 type1,则应仅显示 test6。
如果我切换所有类型,应该只显示 test4 和 test1。
理想的解决方案是用一个图例来做到这一点,是否可以实现?
另外,是否可以像我在上图中尝试的那样使用多个图表来实现这一点?
我似乎无法弄清楚这一点。

一种方法是为每列创建一个选择,绑定到一个复选框。例如:

import altair as alt
import pandas as pd

data = {
    'type1': [1, 0, 0, 1, 0, 1],
    'type2': [1, 1, 1, 1, 0, 0],
    'type3': [1, 0, 0, 1, 1, 0],
    'id': ['test1', 'test2', 'test3', 'test4', 'test5', 'test6'],
    'fuel': [1, 10, 30, 50, 25, 20]
}

sel = [
  alt.selection_single(bind=alt.binding_checkbox(name=field), fields=[field], init={field: False})
  for field in ['type3', 'type2', 'type1']
]

df = pd.DataFrame(data, columns=['id', 'fuel', 'type1', 'type2', 'type3'])

alt.Chart(df).transform_calculate(
    type1='toBoolean(datum.type1)',
    type2='toBoolean(datum.type2)',
    type3='toBoolean(datum.type3)',
).mark_point().encode(
    x='id',
    y='fuel',
    opacity=alt.condition(sel[0] & sel[1] & sel[2], alt.value(1), alt.value(0))
).add_selection(
    *sel
)