how can i sort values based on selection in an altair chart?

One way you can do this is to access the contents of the selection within a calculate transform, using a vega expression to find whether the current column is in the selection. At this point, you can set the order to this encoding:

import altair as alt
from vega_datasets import data

source = data.iowa_electricity()
selection = alt.selection(type='multi', fields=['source'], bind='legend')

alt.Chart(source).add_selection(
    selection
).transform_calculate(
    order=f"indexof({selection.name}.source || [], datum.source)",
).mark_area().encode(
    x="year:T",
    y="net_generation:Q",
    color="source:N",
    opacity=alt.condition(selection, alt.value(1), alt.value(0.1)),
    order=alt.Order("order:N", sort='descending'),
).add_selection(selection)

enter image description here

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top