Can you change the data itself in an interactive Altair plot?

Viewed 138

I'd like to be able to modify the underlying data being charted. For example, I have:

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

This gives a bar chart showing the % full a glass is:

"Glass is x% full" chart

I'd like to be able to drag the slider and have it change the percent full (and empty). Something like:

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

...but that isn't legal. Does Altair support this type of interactivity? I didn't see anything like it in the docs.

2 Answers

You can reference the selector value in a calculate transform; try something like this:

(
    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
    )
)
Related