如何根据 Altair 图表中的选择对值进行排序?

How to sort values based on selection in an Altair chart?

给定一个这样的交互式面积图:

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).mark_area().encode(
    x="year:T",
    y="net_generation:Q",
    color="source:N",
    opacity=alt.condition(selection, alt.value(1), alt.value(0.1))
).add_selection(selection)

我想先对所选值进行排序,以便它们从底部堆叠起来,而不是像下面的示例那样“悬在空中”:

但是,我看不出如何在转换中表达这一点。唯一有效的是 transform_filter(selection) 但这完全删除了未选择的值。

这是不可能的还是我遗漏了什么?

执行此操作的一种方法是访问 calculate transform, using a vega expression 中选择的内容,以查找当前列是否在选择中。此时可以设置顺序为这个编码:

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)