我们可以在Altair的交互式折线图中添加交互式图例吗?

时间:2020-11-06 14:19:27

标签: legend linechart interactive altair

目标:

  1. 将鼠标悬停在折线图中,增加折线的粗细, 使所有其他行变灰,并使图例中的所有其他项变灰 也一样参见interactive line chart
  2. 在图例上单击时,增加线的粗细,将其他所有行涂灰,并在图例中将所有其他项目涂灰 也一样参见interactive legend

我们可以在下面的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

enter image description here

2 个答案:

答案 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

输出: Interactive legend highlights a line in Altair

答案 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

enter image description here