目标:
我们可以在下面的interactive line chart中添加交互式图例吗?
问题:线宽不会随着图例上的选择而改变。
from vega_datasets import data
source = data.stocks()
highlight = alt.selection(type='single', on='mouseover',
fields=['symbol'], nearest=True)
selection = alt.selection_multi(fields=['symbol'], bind='legend', on='mouseover')
base = alt.Chart(source).encode(
x='date:T',
y='price:Q',
color='symbol:N',
tooltip=['symbol']
)
points = base.mark_circle().encode(
opacity=alt.value(0)
).add_selection(
highlight
).properties(
width=600
)
lines = base.mark_line().encode(
opacity=alt.condition(selection, alt.value(1), alt.value(0.2)),
size=alt.condition(~highlight, alt.value(1), alt.value(3))
).add_selection(selection)
points + lines
答案 0 :(得分:0)
为什么要使用两层?
from vega_datasets import data
import altair as alt
source = data.stocks()
selection = alt.selection_multi(fields=['symbol'], bind='legend')
base = alt.Chart(source).mark_line(point=True).encode(
x='date:T',
y='price:Q',
color='symbol:N',
tooltip=['symbol'],
opacity=alt.condition(selection, alt.value(1), alt.value(0.2)),
size=alt.condition(~selection, alt.value(1), alt.value(3))
).add_selection(
selection
)
base
答案 1 :(得分:0)
在突出显示部分添加bind='legend'
接近正确答案;但是,此解决方案会在图例中创建一些具有零不透明度点的奇怪行为。
from vega_datasets import data
source = data.stocks()
highlight = alt.selection(type='single', on='mouseover', fields=['symbol'], nearest=True, bind='legend')
selection = alt.selection_multi(fields=['symbol'], bind='legend', on='mouseover')
base = alt.Chart(source).encode(
x='date:T',
y='price:Q',
color='symbol:N',
tooltip=['symbol']
)
points = base.mark_circle().encode(
opacity=alt.value(0.01)
).add_selection(
highlight
).properties(
width=600
)
lines = base.mark_line().encode(
opacity=alt.condition(selection, alt.value(1), alt.value(0.2)),
size=alt.condition(~highlight, alt.value(1), alt.value(3))
).add_selection(selection)
points + lines