首页 > 解决方案 > 单击图表时,在 Altair 交互式图例中保留多选

问题描述

我在 Altair 中创建了一个带有交互式图例的复合条形图,其中一个图表中的条形图和图例元素都可以选择来过滤另一个图表。当只选择一个图例元素时,这很有效。However, when multiple legend elements are selected, selecting a bar alters the legend selection.

请参阅下面的最小示例。在此图像中,已选择 Crookston 和 Duluth 站点,结果按年份的产量总和图表被过滤到这两个站点。但是,如果我随后单击品种产量总和图表中的满洲条,则图例选择会发生变化,因此仅选择了德卢斯,如图所示。(如果我改为在 Manchuria 栏上按住 shift 单击,则图例中只选择了 Crookston。)期望的结果是让 Crookston 和 Duluth 在图例中保持选中状态。

单击图表时是否可以防止图例的选择发生变化?

import altair as alt
from vega_datasets import data

source = data.barley()

bar_selection = alt.selection_multi(encodings=["y"])
legend_selection = alt.selection_multi(encodings=["color"], bind="legend")

varieties = alt.Chart(source).mark_bar().encode(
    x="sum(yield)",
    y="variety",
    color="site",
    opacity=alt.condition(
        bar_selection, alt.value(1.0), alt.value(0.25)
    ),
).add_selection(bar_selection)

years = alt.Chart(source).mark_bar().encode(
    x="sum(yield)",
    y="year:N",
    color="site",
).transform_filter(
    bar_selection
).transform_filter(
    legend_selection
)

(varieties & years).add_selection(legend_selection)

标签: legendselectionaltairvega-lite

解决方案


推荐阅读