【问题标题】:altair can't create combination of selectionsaltair 无法创建选择组合
【发布时间】:2020-04-22 11:54:27
【问题描述】:

我想创建一个交互式“图例”,允许我选择不同列中数据的组合。 例如,如果我们有这些数据:

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'])

导致:

我现在希望能够可视化不同“类型”的组合。
像这样的东西:

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

【问题讨论】:

    标签: python data-visualization visualization vega-lite altair


    【解决方案1】:

    执行此操作的一种方法是为每列创建一个选择,并绑定到一个复选框。例如:

    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
    )
    

    【讨论】:

    • 非常感谢!!这正是我所需要的。
    猜你喜欢
    • 2020-08-13
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多