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

时间:2020-10-31 19:18:38

标签: altair

给出如下交互式区域图:

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)

我想首先对选定的值进行排序,以使它们从底部开始堆叠,而不像下面的示例那样“悬空”:

https://discord.js.org/#/docs/main/stable/class/GuildMemberRoleManager?scrollTo=highest

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

这是不可能的还是我错过了什么?

1 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是访问calculate transform中的选择内容,使用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)

enter image description here