您可以在交互式 Altair 图中更改数据本身吗?

时间:2021-04-13 17:07:10

标签: python altair

我希望能够修改正在绘制的基础数据。例如,我有:

df = pd.DataFrame({
    'xval': ['full', 'empty'],
    'yval': [25, 75],
})

slider = alt.binding_range(min=0, max=100, step=1, name='cutoff:')
selector = alt.selection_single(name="SelectorName", fields=['cutoff'],
                                bind=slider, init={'cutoff': 25})

(
    alt.Chart(df)
    .mark_bar()
    .encode(
        x='xval',
        y='yval',
    )
    .properties(title='Glass %')
    .add_selection(
        selector
    )
)

这给出了一个条形图,显示了一个玻璃杯的满度百分比:

"Glass is x% full" chart

我希望能够拖动滑块并让它更改已满(和空)的百分比。类似的东西:

...
.encode(
    x='xval',
    y=alt.condition(
        alt.datum.xval == 'full',
        'xval', 100-'xval'
    )
)
...

...但这不合法。 Altair 是否支持这种类型的交互?我在 the docs 中没有看到类似的东西。

2 个答案:

答案 0 :(得分:2)

您可以在计算转换中引用选择器值;尝试这样的事情:

(
    alt.Chart(df)
    .transform_calculate(
        yval = "datum.xval == 'full' ? SelectorName.cutoff : 100 - SelectorName.cutoff"
    )
    .mark_bar()
    .encode(
        x='xval',
        y=alt.Y('yval', scale={'domain': [0, 100]})
    )
    .properties(title='Glass %')
    .add_selection(
        selector
    )
)

答案 1 :(得分:0)

您可以使用带有选择器值的转换过滤器:

(
    alt.Chart(df)
    .mark_bar()
    .encode(
        x='xval',
        y='yval',
    )
    .properties(title='Glass %')
    .add_selection(selector)
    .transform_filter(alt.datum.yval < selector.cutoff)
)

It is briefly mentioned at the end of this section of the docs.