重排序堆叠条形图段#

这个例子使用一个计算转换来检查“site”列的值与图例中点击的值,如果匹配则分配较低的顺序(0)。使用“indexOf”来检查数组中的相等性,这使得通过按住 Shift 键同时点击图例来重新排序多个段成为可能。

import altair as alt
from vega_datasets import data

selection = alt.selection_point(fields=['site'], bind='legend')

source = data.barley.url

alt.Chart(source).mark_bar().transform_calculate(
    site_order=f"if({selection.name}.site && indexof({selection.name}.site, datum.site) !== -1, 0, 1)"
).encode(
    x='sum(yield):Q',
    y='variety:N',
    color='site:N',
    order='site_order:N',
    opacity=alt.when(selection).then(alt.value(0.9)).otherwise(alt.value(0.2))
).add_params(
    selection
)
import altair as alt
from vega_datasets import data

selection = alt.selection_point(fields=['site'], bind='legend')

source = data.barley.url

alt.Chart(source).mark_bar().transform_calculate(
    site_order=f"if({selection.name}.site && indexof({selection.name}.site, datum.site) !== -1, 0, 1)"
).encode(
    x='sum(yield):Q',
    y='variety:N',
    color='site:N',
    order='site_order:N',
    opacity=alt.when(selection).then(alt.value(0.9)).otherwise(alt.value(0.2))
).add_params(
    selection
)
# No channel encoding options are specified in this chart
# so the code is the same as for the method-based syntax.