交互式图例#
以下内容展示了如何通过将选择绑定到 "legend" 来创建一个具有交互式图例的图表。这样的绑定仅在投影在单个字段或编码上时与 selection_point 一起使用。
import altair as alt
from vega_datasets import data
source = data.unemployment_across_industries.url
selection = alt.selection_point(fields=['series'], bind='legend')
alt.Chart(source).mark_area().encode(
alt.X('yearmonth(date):T').axis(domain=False, format='%Y', tickSize=0),
alt.Y('sum(count):Q').stack('center').axis(None),
alt.Color('series:N').scale(scheme='category20b'),
opacity=alt.when(selection).then(alt.value(1)).otherwise(alt.value(0.2))
).add_params(
selection
)
import altair as alt
from vega_datasets import data
source = data.unemployment_across_industries.url
selection = alt.selection_point(fields=['series'], bind='legend')
alt.Chart(source).mark_area().encode(
alt.X('yearmonth(date):T', axis=alt.Axis(domain=False, format='%Y', tickSize=0)),
alt.Y('sum(count):Q', stack='center', axis=None),
alt.Color('series:N', scale=alt.Scale(scheme='category20b')),
opacity=alt.when(selection).then(alt.value(1)).otherwise(alt.value(0.2))
).add_params(
selection
)