【问题标题】:Altair: how do I get the values from a dropdown menuAltair:如何从下拉菜单中获取值
【发布时间】:2020-10-22 16:24:59
【问题描述】:

生成图片的代码如下:

input_dropdown = alt.binding_select(options=['Brand','Function','Category'])
selection = alt.selection_single(name='Color By', fields=['categories'], bind=input_dropdown)
alt.Chart(df_PCs).mark_circle().encode(x="PC1:Q", y="PC2:Q", color="Function:N", tooltip=['Name']).add_selection(selection)

我想做的是按品牌、功能或类别为点着色,无论下拉菜单中的值是什么。有没有办法获取下拉菜单的值?比如selection.value()?

【问题讨论】:

    标签: altair


    【解决方案1】:

    解决此问题的最佳方法类似于Dynamically Change Y-Axis Field in Encoding Based on Selection Vega-Lite 中的 Vega-Lite 答案

    选择不能过滤列标题,只能过滤列值。幸运的是,您可以使用fold transform 堆叠多个列并将这些列名转换为列值。

    下面是一个折叠变换的例子,它结合一个选择框来选择要着色的列:

    import altair as alt
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({
        'x': np.random.randn(100),
        'y': np.random.randn(100),
        'c1': np.random.randint(0, 3, 100),
        'c2': np.random.randint(0, 3, 100),
        'c3': np.random.randint(0, 3, 100),
    })
    
    selector = alt.selection_single(
        name='Color by',
        fields=['column'],
        bind=alt.binding_select(options=['c1', 'c2', 'c3']),
        init={'column': 'c1'}
    )
    
    alt.Chart(df).transform_fold(
        ['c1', 'c2', 'c3'], as_=['column', 'value']
    ).transform_filter(
        selector
    ).mark_point().encode(
        x='x:Q',
        y='y:Q',
        color='value:Q',
        column='column:N'
    ).add_selection(
        selector
    )
    

    对于您的数据,它可能看起来像这样(尽管我无法对其进行测试,因为数据未包含在问题中)

    selection = alt.selection_single(
        fields=['column'],
        bind=alt.binding_select(
            name="Color by: ",
            options=['Brand','Function','Category']
        ),
        init={'column':'Function'}
    )
    
    alt.Chart(df_PCs).transform_fold(
        ["Brand", "Function", "Category"],
        as_=['column', 'value']
    ).transform_filter(
        selection
    ).mark_point().encode(
        x="PC1:Q",
        y="PC2:Q",
        color="value:N",
        column="column:N",
        tooltip=['Name:N']
    ).add_selection(selection)
    

    【讨论】:

    • 感谢您的回答。我尝试了我的数据,但它不起作用。我想知道是不是因为你的颜色使用了数字数据点,而我有分类数据?
    • 请编辑您的问题以添加错误的Minimal reproducible example
    • 我添加了另一个示例,该示例基于您屏幕截图中显示的数据。
    • 非常感谢!我意识到在我尝试重现您的代码时存在一个愚蠢的错误......
    最近更新 更多